Guide

Lifetime annotations

Sometimes Rust needs your help to see how references are connected. You give that help with lifetime annotations.

The 'a syntax

A lifetime is a name that starts with a quote, like 'a. You declare it in angle brackets, then use it on references.

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

Read &'a str as "a reference to a str that is valid for 'a". Using 'a without declaring <'a> is error E0261.

Linking inputs and output

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

The result might be x or y. So 'a says: the result is valid only while both inputs are valid. At each call, Rust picks the shorter of the two lifetimes.

let a = String::from("apple");let r;{    let b = String::from("kiwi");    r = longest(&a, &b);}println!("{r}"); // error E0597: b is gone

Annotations only describe

An annotation never makes a value live longer. Values still live until the end of their owner's scope. 'a only tells the compiler how references relate, so it can check your code. The compiler checks calls using the signature, not the body.

A string literal like "kiwi" is stored in the program itself, so a reference to it is valid for the whole run.

Missing lifetimes

fn longest(x: &str, y: &str) -> &str // error E0106

With two reference inputs, Rust can't tell which one the result borrows from. It asks you to name a lifetime. With only one reference input, it can guess (next unit).

Remember

  • Declare with <'a>, use with &'a T.
  • The same 'a on inputs and output links them.
  • Annotations describe; they don't extend.
  • E0106 means "tell me what the result borrows from".