TExcelTAD
Home › Rust › Rust Lifetimes

Rust Lifetimes

Every reference in Rust has a lifetime: the span of code during which the reference is valid. Most of the time lifetimes are inferred and you never write them. But when a function takes several references and returns one, the compiler sometimes needs a hint about how they are related. Lifetime annotations provide that hint.

Note: Lifetime annotations never change how long a value lives. They only describe relationships between references so the compiler can check them.

The problem lifetimes solve

The borrow checker's job is to make sure no reference outlives the data it points to. Here is the classic mistake it catches:

rust
fn main() {
    let r;
    {
        let short_lived = 5;
        r = &short_lived;
    } // short_lived is dropped here
    println!("{}", r); // r would point to freed memory
}
text
error[E0597]: `short_lived` does not live long enough
 --> src/main.rs:5:13
  |
4 |         let short_lived = 5;
  |             ----------- binding `short_lived` declared here
5 |         r = &short_lived;
  |             ^^^^^^^^^^^^ borrowed value does not live long enough
6 |     } // short_lived is dropped here
  |     - `short_lived` dropped here while still borrowed
7 |     println!("{}", r); // r would point to freed memory
  |                    - borrow later used here

Within one function the compiler can see everything. Across function boundaries it relies on the function signature — and that is where annotations come in.

Lifetime annotation syntax

A lifetime parameter starts with an apostrophe and is usually short: 'a, 'b. It is declared in angle brackets after the function name, like a generic type, and then attached to references:

Written Meaning
&i32 a reference (lifetime inferred)
&'a i32 a reference that lives at least as long as 'a
&'a mut i32 a mutable reference with lifetime 'a
&'static str a reference valid for the entire program

A function that needs annotations

This function returns whichever of two strings is longer. The compiler can't know whether the result borrows from a or b, so we tell it: "the result lives as long as both inputs".

rust · try it yourself
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    let city1 = String::from("Copenhagen");
    let city2 = String::from("Oslo");

    let result = longer(&city1, &city2);
    println!("Longer name: {}", result);
}
Longer name: Copenhagen

'a becomes the shorter of the two input lifetimes, and the returned reference may only be used while both inputs are still alive. Without <'a> you would get "missing lifetime specifier".

Here is what the annotation protects you from:

rust
fn main() {
    let outer = String::from("long string");
    let result;
    {
        let inner = String::from("xyz");
        result = longer(&outer, &inner);
    } // inner dropped here
    println!("{}", result); // error: `inner` does not live long enough
}

Lifetime elision: when you don't need to write them

Writing 'a everywhere would be noisy, so the compiler applies elision rules:

  1. Each reference parameter gets its own lifetime.
  2. If there is exactly one input reference, the output gets that same lifetime.
  3. If one of the parameters is &self or &mut self, the output gets the lifetime of self.

That's why this function needs no annotations — there's only one input reference:

rust · try it yourself
fn initials(name: &str) -> &str {
    let end = name.find(' ').unwrap_or(name.len());
    &name[..1.min(end)]
}

fn shortest_word(text: &str) -> &str {
    let mut best = text;
    for word in text.split_whitespace() {
        if word.len() < best.len() {
            best = word;
        }
    }
    best
}

fn main() {
    println!("{}", initials("Grace Hopper"));
    println!("{}", shortest_word("lifetimes are not so scary"));
}
G
so

Lifetimes in structs

A struct that holds a reference must declare a lifetime, which promises that the struct cannot outlive the data it borrows.

rust · try it yourself
struct Highlight<'a> {
    text: &'a str,
    page: u32,
}

impl<'a> Highlight<'a> {
    fn describe(&self) -> String {
        format!("p.{}: \"{}\"", self.page, self.text)
    }

    fn first_word(&self) -> &str {
        self.text.split(' ').next().unwrap_or("")
    }
}

fn main() {
    let book = String::from("Ownership is Rust's most unique feature. It enables safety.");
    let first_sentence = book.split(". ").next().unwrap();

    let h = Highlight { text: first_sentence, page: 59 };
    println!("{}", h.describe());
    println!("Starts with: {}", h.first_word());
}
p.59: "Ownership is Rust's most unique feature"
Starts with: Ownership

Highlight borrows from book, so book must stay alive as long as h is used. first_word needs no annotation thanks to elision rule 3.

The 'static lifetime

'static means "valid for the whole program". All string literals have type &'static str because they're stored in the program binary.

rust · try it yourself
const GREETING: &'static str = "Hello from the binary!";

fn level_name(level: u8) -> &'static str {
    match level {
        0 => "beginner",
        1 => "intermediate",
        _ => "expert",
    }
}

fn main() {
    println!("{}", GREETING);
    for lvl in 0..3 {
        println!("level {} = {}", lvl, level_name(lvl));
    }
}
Hello from the binary!
level 0 = beginner
level 1 = intermediate
level 2 = expert

Tip: If the compiler suggests adding 'static to fix an error, think twice. Often the real fix is to return an owned value (String) instead of a reference.

Test yourself

What do lifetime annotations like 'a do?

  1. Make values live longer
  2. Describe how the lifetimes of references relate, so the compiler can check them
  3. Free memory early
  4. Make references mutable

Why does fn first(s: &str) -> &str need no lifetime annotation?

  1. &str never needs lifetimes
  2. Elision: with exactly one input reference, the output gets its lifetime
  3. The function is too short
  4. It returns a 'static value

What is the type of the literal "hi"?

  1. String
  2. &'static str
  3. &'a String
  4. char