FerrousPath

Level 2 · Practitioner· Lesson 3 of 8 · 30 min

Lifetimes

How the compiler reasons about how long references stay valid, what the annotations mean, and when you need to write them.

References must not outlive their referent

Every reference has a lifetime: the region of code in which it is valid. The borrow checker’s job is to ensure no reference is used after the value it points to is gone.

fn main() {
    let r;
    {
        let x = 5;
        r = &x; // ❌ error[E0597]: `x` does not live long enough
    }           // x is dropped here…
    println!("{r}"); // …but r is used here
}

Most of the time lifetimes are inferred and you never write them. Annotations become necessary when the compiler cannot tell how the references in a signature relate.

Why annotations exist

fn longest(a: &str, b: &str) -> &str { // ❌ error[E0106]: missing lifetime specifier
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    println!("{}", longest("ab", "abc"));
}

The returned reference borrows from a or b, but which? The compiler checks each function in isolation, using only signatures of the functions it calls. It needs the signature to say how long the result is valid:

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

fn main() {
    let first = String::from("a long string");
    let result;
    {
        let second = String::from("short");
        result = longest(&first, &second).to_string(); // copy out while both are alive
    }
    println!("{result}");
}

Read <'a> as: “there is some region 'a for which both inputs are valid, and the output is valid for that region too”. At each call the compiler picks 'a as the overlap of the two arguments’ lifetimes. The annotation does not make anything live longer — it is a contract the caller must be able to satisfy.

If the result only ever comes from one argument, say so, and callers get more freedom:

fn first_word<'a>(text: &'a str, _separator: &str) -> &'a str {
    text.split_whitespace().next().unwrap_or("")
}

fn main() {
    let text = String::from("hello world");
    let word;
    {
        let sep = String::from(" ");
        word = first_word(&text, &sep);
    } // sep is gone, and that is fine: the result does not borrow from it
    println!("{word}");
}

Lifetime elision

You have written many functions returning references without annotations. Three rules fill them in:

  1. Each elided input lifetime becomes its own parameter.
  2. If there is exactly one input lifetime, it is assigned to all outputs.
  3. If one input is &self or &mut self, its lifetime is assigned to all outputs.

If the outputs are still undetermined after these rules, you must annotate. The rules are purely syntactic conveniences — they never look at the function body.

Structs that hold references

A struct that stores a reference needs a lifetime parameter: the struct cannot outlive what it borrows.

#[derive(Debug)]
struct Excerpt<'a> {
    text: &'a str,
}

impl<'a> Excerpt<'a> {
    fn first_sentence(source: &'a str) -> Self {
        Excerpt { text: source.split('.').next().unwrap_or(source) }
    }

    // Elision rule 3: the result borrows from self.
    fn words(&self) -> usize {
        self.text.split_whitespace().count()
    }
}

fn main() {
    let novel = String::from("Call me Ishmael. Some years ago…");
    let e = Excerpt::first_sentence(&novel);
    println!("{e:?} has {} words", e.words());
}

This is how zero-copy parsers work: the parsed structure is full of slices pointing into the input buffer, and the compiler guarantees the buffer outlives them.

Design advice. If lifetime annotations are spreading through your program and fighting you, ask whether the struct should own its data instead (String rather than &str). Borrowing in structs is an optimisation; owning is the default.

'static

'static is the lifetime of the whole program. String literals are &'static str because they live in the binary.

As a bound, T: 'static means something subtler: T holds no borrowed data that could expire. Owned types such as String and Vec<u8> satisfy it. You will see it on std::thread::spawn, which requires its closure to be 'static because the new thread may outlive the caller’s stack frame.

When an error message suggests adding 'static, it is rarely the right fix. Usually it means you are trying to keep a borrow longer than its owner lives, and should own the data instead.

Lifetimes are regions, not scopes

The borrow checker reasons about the control-flow graph, a system called non-lexical lifetimes (NLL). A borrow lasts from its creation to its last use along each path.

fn main() {
    let mut scores = vec![1, 2, 3];
    let first = &scores[0];
    println!("{first}");  // last use of `first`
    scores.push(4);       // OK: the shared borrow has ended
    println!("{scores:?}");
}

Level 5 examines NLL and its successor, Polonius, in detail.

Exercises

  1. Write fn longest_word<'a>(text: &'a str) -> &'a str. Then delete the annotations and explain why it still compiles.
  2. Write a struct Splitter<'a> { rest: &'a str, sep: char } with a method next_piece(&mut self) -> Option<&'a str> that returns successive pieces.
  3. Why is this rejected, and what are two fixes? fn make() -> &str { let s = String::from("x"); &s }
Solution to 2
struct Splitter<'a> { rest: &'a str, sep: char }

impl<'a> Splitter<'a> {
    fn next_piece(&mut self) -> Option<&'a str> {
        if self.rest.is_empty() {
            return None;
        }
        match self.rest.split_once(self.sep) {
            Some((head, tail)) => { self.rest = tail; Some(head) }
            None => { let last = self.rest; self.rest = ""; Some(last) }
        }
    }
}

fn main() {
    let mut s = Splitter { rest: "a,b,c", sep: ',' };
    while let Some(p) = s.next_piece() {
        println!("{p}");
    }
}

Note the return type is Option<&'a str>, not tied to &mut self. The pieces borrow from the original text, so they remain valid after the splitter is modified or dropped.

Check your understanding

Pick an answer to see the explanation.

  1. 1.What does a lifetime annotation such as 'a do?

  2. 2.Under the elision rules, what is the lifetime of the return value of fn get(&self, key: &str) -> &str?

  3. 3.What does the bound T: 'static mean?

Key terms in this lesson

Finished the lesson and the exercises?