A Rust lifetime annotation like 'a does not make a value live longer. It records, in the signature, which input a returned reference borrows from. The borrow checker uses that annotation together with the point where each reference is last used to work out how long a borrow stays valid.

Adding 'a wherever the compiler suggests it usually gets code to compile. I wanted to work out what that suggestion asks of the caller, and which rules decide when the annotation can be left out. Every example below was compiled and run with rustc 1.94.1, edition 2021.

Borrow regions

This code borrows the first element of a vector, then pushes onto the vector.

fn main() {
    let mut scores = vec![10, 20, 30];
    let first = &scores[0];
    scores.push(40);
    println!("first = {first}");
}

The compiler rejects it.

error[E0502]: cannot borrow `scores` as mutable because it is also borrowed as immutable
 --> nll_err.rs:4:5
  |
3 |     let first = &scores[0];
  |                  ------ immutable borrow occurs here
4 |     scores.push(40);
  |     ^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("first = {first}");
  |                        ----- immutable borrow later used here

push may reallocate the vector’s buffer, which would free the memory first points to. So a mutable borrow is not allowed while an immutable borrow is still live. The third marker, later used here, is the reason the immutable borrow counts as live: first is used again on line 5, so the borrow taken on line 3 extends to line 5.

Moving the println! above the push makes it compile.

fn main() {
    let mut scores = vec![10, 20, 30];
    let first = &scores[0];
    println!("first = {first}");
    scores.push(40); // the println above is the last use of first
    println!("len = {}", scores.len());
}

The variable first is still in scope until the end of main. The borrow, however, ends at its last use in println! and does not overlap the push. There is an exception: if the type holding the reference implements Drop, the drop that runs at the end of the scope counts as a use, and the borrow lasts until the end of the scope.

Variable scope vs. borrow region (NLL)Rejected (E0502)scope&&mutlet first = &scores[0];scores.push(40);println!("{first}");}Compilesscope&&mutlet first = &scores[0];println!("{first}");scores.push(40);}scope of the variable firstimmutable borrow by first — until its last usemutable borrow by push

Computing borrow regions from uses instead of variable scopes is called NLL (non-lexical lifetimes). It shipped first for the 2018 edition in Rust 1.31 and reached the 2015 edition in 1.36. In 1.63 the previous scope-based borrow checker was removed from rustc, so rustc 1.63 and later compute borrow regions this way in every edition.

Where a returned reference comes from

Inside a function the compiler can see every use. Across a function boundary it cannot: the caller has to decide what the return value borrows from the signature alone, without looking at the body.

A function that strips a root directory prefix from a path does not compile without lifetime annotations.

fn strip_root(path: &str, root: &str) -> &str {
    path.strip_prefix(root).unwrap_or(path)
}
error[E0106]: missing lifetime specifier
 --> strip_elide.rs:1:42
  |
1 | fn strip_root(path: &str, root: &str) -> &str {
  |                     ----        ----     ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `path` or `root`
help: consider introducing a named lifetime parameter
  |
1 | fn strip_root<'a>(path: &'a str, root: &'a str) -> &'a str {
  |              ++++        ++             ++          ++

The help line states the problem: the signature does not say whether the result comes from path or root. The suggested fix ties both to 'a. Accept it and the function compiles, but some calls to it are rejected.

fn strip_root<'a>(path: &'a str, root: &'a str) -> &'a str {
    path.strip_prefix(root).unwrap_or(path)
}

fn main() {
    let path = String::from("/srv/app/config.toml");
    let relative;
    {
        let root = String::from("/srv/app/");
        relative = strip_root(&path, &root);
    } // root dropped
    println!("{relative}");
}
error[E0597]: `root` does not live long enough
  --> strip_err.rs:10:38
   |
 9 |         let root = String::from("/srv/app/");
   |             ---- binding `root` declared here
10 |         relative = strip_root(&path, &root);
   |                                      ^^^^^ borrowed value does not live long enough
11 |     } // root dropped
   |     - `root` dropped here while still borrowed
12 |     println!("{relative}");
   |                -------- borrow later used here

The result points only into path. But the signature says “the result is valid only while both path and root are alive”, so the compiler refuses to let relative be used after root is dropped. At the call site, the compiler checks against the signature, not the body.

Putting 'a only on path, the actual source of the result, makes the same call compile. The unannotated root gets a lifetime of its own under rule 1 of the next section.

fn strip_root<'a>(path: &'a str, root: &str) -> &'a str {
    path.strip_prefix(root).unwrap_or(path)
}

The contract binds the body too. Change the body to return root under the same signature, and now the function definition is rejected.

fn strip_root<'a>(path: &'a str, root: &str) -> &'a str {
    if path.starts_with(root) { root } else { path }
}
error[E0621]: explicit lifetime required in the type of `root`
 --> strip_body_err.rs:2:33
  |
2 |     if path.starts_with(root) { root } else { path }
  |                                 ^^^^ lifetime `'a` required

One signature drives two checks. The body is checked to return only from the sources the signature names. The caller is checked to keep those inputs alive as long as the signature requires. The more inputs share the same 'a, the more the caller has to guarantee. So I judged the compiler’s suggestion to be a starting point, and 'a to belong only on the inputs the result can borrow from. If the function may return root, tying both inputs to 'a as suggested is the right signature.

Elision rules

Not every function that takes and returns references needs 'a. This one compiles without any annotation.

fn file_name(path: &str) -> &str {
    path.rsplit('/').next().unwrap_or(path)
}

The Rust Reference defines what the compiler fills in when lifetimes are elided.

  1. Each elided lifetime in the parameters becomes a distinct lifetime parameter
  2. If exactly one lifetime is used in the parameters, it is assigned to all elided output lifetimes
  3. If a method’s receiver is &self or &mut self, the lifetime of that reference to self is assigned to all elided output lifetimes

file_name has a single input reference, so rule 2 turns it into fn file_name<'a>(path: &'a str) -> &'a str. strip_root gets two distinct lifetimes from rule 1, and neither rule 2 nor rule 3 applies, so the output lifetime cannot be determined. The Reference makes that an error, which is the E0106 above.

SignatureRules appliedOutcome
fn file_name(&str) -> &str1, 2output = the only input
fn strip_root(&str, &str) -> &str1output undetermined (E0106)
fn get(&self, &str) -> &str1, 3output = the self reference

Rule 3 gives the intended result for common methods. For a struct that holds a reference, it may not.

Structs that hold references

This struct splits an HTTP request line on spaces and hands out tokens. It borrows the input as &str instead of copying it, so the struct takes a lifetime parameter 'a. Tokens<'a> reads as “this value borrows a string that is valid for 'a”.

struct Tokens<'a> {
    rest: &'a str,
}

impl<'a> Tokens<'a> {
    fn next_token(&mut self) -> Option<&str> {
        let trimmed = self.rest.trim_start();
        if trimmed.is_empty() {
            return None;
        }
        let end = trimmed.find(' ').unwrap_or(trimmed.len());
        let (token, rest) = trimmed.split_at(end);
        self.rest = rest;
        Some(token)
    }
}

fn main() {
    let line = String::from("GET /health HTTP/1.1");
    let mut tokens = Tokens { rest: &line };
    let method = tokens.next_token();
    let path = tokens.next_token();
    println!("{method:?} {path:?}");
}

This code, which takes two tokens and uses them together, does not compile.

error[E0499]: cannot borrow `tokens` as mutable more than once at a time
  --> parser_err.rs:22:16
   |
21 |     let method = tokens.next_token();
   |                  ------ first mutable borrow occurs here
22 |     let path = tokens.next_token();
   |                ^^^^^^ second mutable borrow occurs here
23 |     println!("{method:?} {path:?}");
   |                ------ first borrow later used here

The return type Option<&str> has an elided lifetime, and rule 3 gives it the lifetime of &mut self. So method comes out of the mutable borrow of tokens, not out of line. Because method is used on line 23, the first mutable borrow lasts until line 23 and overlaps the second next_token call on line 22.

The tokens really are slices of line. Writing the struct’s 'a in the return type makes the signature say so.

    fn next_token(&mut self) -> Option<&'a str> {
Some("GET") Some("/health")

Now each &mut self borrow ends when its next_token call returns. method and path borrow only line, so they can be used freely while line is alive.

Borrow regions by next_token return type-> Option<&str> · rejected (E0499)line#1#2let mut tokens = Tokens { rest: &line };let method = tokens.next_token();let path = tokens.next_token();println!("{method:?} {path:?}");-> Option<&'a str> · compilesline#1#2let mut tokens = Tokens { rest: &line };let method = tokens.next_token();let path = tokens.next_token();println!("{method:?} {path:?}");immutable borrow of line (tokens · method · path)&mut tokens borrow taken by each next_token call

When a method on a reference-holding struct returns a reference, I found it worth checking first whether the reference comes from the struct itself or from the data the struct borrows. If it comes from the borrowed data and elision decides the lifetime, the result is tied to a borrow of the struct.

'static on references and in bounds

'static is a single lifetime: the whole run of the program. What it requires differs between a reference type and a bound on a type parameter.

On a reference type, &'static str is a reference that stays valid until the program ends. String literals are the typical case: they live in the binary and are never freed.

As a trait bound, T: 'static is different. Rust by Example defines it as “the type does not contain any non-static references”. It does not mean the value must live until the program ends. A value that owns its data and holds no references, such as a String built at runtime, always satisfies the bound.

use std::fmt::Debug;
use std::thread;

fn log_later<T: Debug + Send + 'static>(value: T) -> thread::JoinHandle<()> {
    thread::spawn(move || println!("{value:?}"))
}

fn main() {
    let name = String::from("worker-1"); // a String built at runtime
    log_later(name).join().unwrap();

    let label: &'static str = "literal"; // a string stored in the binary
    log_later(label).join().unwrap();
}
"worker-1"
"literal"

name is a local created in main, yet it passes the 'static bound. Ownership moves to the new thread, so nothing borrowed is left behind. Pass &name instead and it is rejected.

// the use declarations and log_later are the same as above
fn main() {
    let name = String::from("worker-1");
    log_later(&name).join().unwrap();
}
error[E0597]: `name` does not live long enough
  --> static_err.rs:10:15
   |
 9 |     let name = String::from("worker-1");
   |         ---- binding `name` declared here
10 |     log_later(&name).join().unwrap();
   |     ----------^^^^^-
   |     |         |
   |     |         borrowed value does not live long enough
   |     argument requires that `name` is borrowed for `'static`
11 | }
   | - `name` dropped here while still borrowed

The bound on log_later comes from the signature of std::thread::spawn, F: FnOnce() -> T + Send + 'static. The compiler cannot know when a new thread will finish, so whatever is sent to it must not contain non-'static references. A &'static str like label above passes even though it is a reference.

If the code guarantees when the threads finish, locals can be lent to them. std::thread::scope, stabilized in Rust 1.63, joins every thread spawned inside the scope before the scope returns.

use std::thread;

fn main() {
    let name = String::from("worker-1");
    thread::scope(|s| {
        s.spawn(|| println!("{name}"));
    }); // every thread is joined before the scope returns
    println!("still own {name}");
}
worker-1
still own worker-1

With the guarantee that the thread finishes before name does, 'static is no longer needed. The thread only borrows name, so main still owns it after the scope ends.

Wrapping up

Within a function, the borrow checker computes borrow regions from where each reference is used again. At a function boundary, it treats the lifetime annotations in the signature as a contract and checks the body and the caller against it separately. Elision rules write that contract for common signatures, but when the contract they pick differs from the actual source, as with methods on a reference-holding struct, 'a has to be written by hand. A bound like T: 'static is not a demand to keep a value alive either; it checks that no borrowed reference is left behind. In each case, editing an annotation leaves how long values live untouched and changes what the compiler checks.

References