Rust

Lifetime Annotations Basics

admin by @admin ADMIN
2h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Lifetimes are how Rust proves references don't outlive what they point to. Most are inferred — but functions returning references from arguments need explicit `'a` to relate input and output.
Rust
Raw
// The compiler needs to know: the returned reference lives as long as
// the SHORTER of the two inputs. The 'a lifetime expresses that.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() >= y.len() { x } else { y }
}

fn main() {
    let s1 = String::from("long string is long");
    let result;
    {
        let s2 = String::from("short");
        result = longest(s1.as_str(), s2.as_str());
        // result borrows from s2 — must be used while s2 is still alive
        println!("longest: {result}");
    }
    // println!("{result}");   // ❌ s2 went out of scope
}

// Struct that holds a reference also needs a lifetime parameter:
struct Excerpt<'a> {
    text: &'a str,
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.