Lifetime (Rust)

A lifetime is the scope for which a reference is valid. Lifetime annotations like 'a tell the compiler how the lifetimes of multiple references relate so it can guarantee no reference outlives its data.

Rust

Every reference in Rust has a lifetime — the region of code where it stays valid. Most of the time the compiler infers lifetimes automatically (lifetime elision), so you never write them. They become explicit only when a function returns a reference and the compiler can't tell which input it came from.

Lifetime annotations such as 'a are not commands that change how long data lives; they are descriptions of relationships. Writing fn longest<'a>(x: &'a str, y: &'a str) -> &'a str promises the returned reference lives at least as long as both inputs.

Lifetimes are the part of Rust beginners find hardest because the errors are abstract. The fix is usually to make ownership clearer: return an owned String instead of a borrowed &str, or give a struct ownership of its data rather than holding references.

Syntax

fn first<'a>(x: &'a str, y: &str) -> &'a str { x }

Examples

Rust

fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    println!("{}", longest("rust", "go"));
}

Output:

rust

Learn it in a lesson

See also

Back to the Dictionary