Rust Tutorial · Ownership and Borrowing · Lesson 12 of 29

Rust Lifetimes

What lifetime annotations mean, when the compiler needs them, and how they prevent dangling references.

Create a free account to save this page, take notes and track your progress. Sign in

Why lifetimes exist

A reference must never outlive the value it points to. Usually the compiler works this out itself; when a function returns a reference derived from several inputs, you tell it how they relate with a lifetime parameter such as 'a:

A function returning a borrowed value
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    let first = String::from("borrow checker");
    let result;
    {
        let second = String::from("rust");
        result = longer(&first, &second);
        println!("longer: {result}");
    }
    // println!("{result}");   // error: `second` does not live long enough
}

Output

longer: borrow checker

Run this on your computer — see “Get Started” for setup.

<'a> says: the returned reference lives as long as both inputs do. Lifetimes don't change how long values live; they describe relationships the compiler then checks.

Structs holding references

A struct that stores a reference needs a lifetime too:

A struct with a lifetime
struct Excerpt<'a> {
    text: &'a str,
}

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

fn main() {
    let article = String::from("Rust is fast. It is also safe.");
    let excerpt = Excerpt { text: &article };
    println!("{}", excerpt.first_sentence());
}

Output

Rust is fast

Run this on your computer — see “Get Started” for setup.

If lifetimes get complicated, owning the data (String instead of &str) is often the simpler design.

Test yourself

Do lifetime annotations change how long a value lives?

  1. Yes, they extend it
  2. No, they describe relationships the compiler checks
  3. Yes, they make it static
  4. Only in unsafe code
Show answer

Answer: No, they describe relationships the compiler checks

Was this page helpful?