Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Concepts

Lifetimes in Rust

Reference for Rust lifetimes: what 'a means, how annotations relate references, the three elision rules, lifetimes in structs, 'static and common errors.

A lifetime is the span of code during which a reference is valid. Every reference has one, but most are inferred. You write lifetime annotations such as 'a only when the compiler cannot work out how the lifetimes of several references relate, typically in function signatures and in structs that hold references.

An annotation does not make anything live longer. It is a contract that tells the compiler: "the output reference is valid no longer than these input references". The borrow checker then verifies that every caller and the function body keep that contract.

Rust
fn longer<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() >= y.len() { x } else { y }
}

Try it

Rust Relating inputs and outputs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust A struct that borrows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust A dangling reference is rejected

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
fn name<'a, 'b>(x: &'a T, y: &'b U) -> &'a V            // generic lifetime parameters
struct Holder<'a> { field: &'a str }                      // struct with a borrowed field
impl<'a> Holder<'a> { fn get(&self) -> &'a str { self.field } }
fn needs<'a, T: 'a>(x: &'a T)                             // T outlives 'a
fn long<'a, 'b: 'a>(x: &'a str, y: &'b str) -> &'a str   // 'b outlives 'a
fn hr<F>(f: F) where F: for<'x> Fn(&'x str) -> &'x str   // higher-ranked bound
let s: &'static str = "text";                             // lives for the whole program
Form Meaning
'a A named lifetime parameter, declared in angle brackets like a type parameter.
&'a T A reference valid for 'a.
'b: 'a 'b outlives 'a (reads "'b lasts at least as long as 'a").
T: 'a Every reference inside T is valid for at least 'a.
'static The whole program run. String literals and leaked data have it.
'_ An anonymous lifetime, "infer this one", for example Words<'_>.

Errors: E0106 (missing lifetime specifier), E0597 (value does not live long enough), E0515 (returning a reference to a local), E0499/E0502 (conflicting borrows).

Elision rules

If you leave lifetimes out of a function signature, the compiler applies three rules in order:

  1. Every elided input lifetime becomes a separate lifetime parameter.
  2. If there is exactly one input lifetime, it is assigned to all elided output lifetimes.
  3. If one of the inputs is &self or &mut self, its lifetime is assigned to all elided outputs.

If the output lifetimes are still undetermined, you must annotate. So fn first(s: &str) -> &str is fine (rule 2), fn get(&self, k: &str) -> &str is fine (rule 3, tied to self), and fn pick(a: &str, b: &str) -> &str fails with E0106.

Usage notes

  • 'static is not "forever alive data" for bounds. T: 'static means T contains no non-static borrows; owned types like String satisfy it. Thread spawning needs it because the thread may outlive the caller.
  • Returning a reference to a local is impossible. Return the owned value instead.
  • A struct with a reference cannot outlive what it borrows. If that is painful, store owned data (String, Arc) or indexes.
  • Methods that return a field reference can use 'a from the struct (-> &'a str) when the result should outlive the &self borrow, as in the iterator above.
  • Variance: &'a T is covariant in 'a, so a longer-lived reference can be used where a shorter one is expected. &mut T is invariant in T.
  • In trait objects, Box<dyn Trait> means Box<dyn Trait + 'static>; write Box<dyn Trait + 'a> to hold borrows.
  • Lifetimes exist only at compile time. They do not change the generated code.
  • Edition 2024: return-position impl Trait captures all in-scope lifetimes by default; see Editions.