What is lifetime elision in Rust

Lifetime elision is a set of compiler rules that automatically infers reference lifetimes in Rust functions, removing the need for explicit annotations in simple cases.

Lifetime elision is a set of rules the Rust compiler uses to automatically infer lifetime parameters for references in functions, so you don't have to write them explicitly. The compiler applies three specific rules: if every parameter is a reference and there is only one, that lifetime is assigned to all output references; if there are multiple input references but one is &self, that lifetime is assigned to all output references; otherwise, the compiler rejects the code if you haven't annotated lifetimes.

// The compiler elides the lifetime here, treating it as fn first<'a>(s: &'a str) -> &'a str
fn first(s: &str) -> &str {
    s
}

// This requires explicit annotation because it breaks the elision rules
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}