What Is Lifetime Elision and When Does It Apply?

Lifetime elision is a compiler feature that automatically infers reference lifetimes in Rust functions, reducing the need for explicit annotations.

Lifetime elision is a set of rules the Rust compiler uses to infer lifetime parameters for references in function signatures when they are not explicitly annotated. It applies to functions and methods where the compiler can unambiguously determine the relationship between input and output references, preventing the need for verbose lifetime syntax in common cases.

fn first_word(s: &str) -> &str {
    // The compiler infers: fn first_word<'a>(s: &'a str) -> &'a str
    let bytes = s.as_bytes();
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }
    &s[..]
}

The three elision rules are: 1) Each input reference gets its own lifetime, 2) If there is exactly one input lifetime, it is assigned to all output references, and 3) If there are multiple input references but the function returns &self, the lifetime of self is assigned to all output references.