IntermediateLesson 10 of 157 min read

Lifetimes: How the Compiler Knows a Reference Is Valid

Understand Rust lifetimes with a working longest-reading function, a struct that holds a reference, and the real compiler errors for a missing lifetime specifier and for a dangling reference.

In this lesson you will

  • Explain what a lifetime is
  • Annotate a function with a lifetime
  • Store a reference in a struct
  • Read E0106 and E0597

About 28 minutes

A reference must not outlive its data

Every reference in Rust has a lifetime, the part of the program during which the value it points to is valid, and the compiler checks that a reference is never used after the value is gone. In most code you never write lifetimes, since the compiler infers them. They appear in your code only when a function returns a reference, or a struct holds one, and the compiler cannot tell from the signature which input the output is tied to. Then you annotate with a name such as ‘a, which says “these references live at least as long as each other”. The annotation does not change how long anything lives: it only describes the relationship, so that the compiler can check it.

Ines wants a function that picks the longer of two station names. If the function returns one of its inputs, the compiler needs to know that the result is valid as long as both of them. The signature fn longer(a: &’a str, b: &’a str) -> &’a str says exactly that: the result lives no longer than the shorter of the two inputs. The compiler also applies three elision rules, so that a function with a single reference parameter, or a method with &self, needs no annotation at all. A struct that holds a reference needs a lifetime parameter too, because a struct must not outlive the text it borrows.

Case Needs annotation?
fn first(s: &str) -> &str No, one input, elided
fn longer(a: &str, b: &str) -> &str Yes, which input?
struct Parser { text: &’a str } Yes
fn get(&self) -> &str No, tied to self
‘static Lives for the whole program, like a string literal
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn first_word(s: &str) -> &str {
    s.split_whitespace().next().unwrap_or("")
}

struct Station<'a> {
    line: &'a str,
}

impl<'a> Station<'a> {
    fn id(&self) -> &str { self.line.split(',').next().unwrap_or("") }
    fn field(&self, n: usize) -> Option<&'a str> { self.line.split(',').nth(n) }
}

fn main() {
    let a = String::from("North ridge");
    let result;
    {
        let b = String::from("Bay");
        result = longer(a.as_str(), b.as_str()).to_string();
        println!("inside the block: {}", longer(&a, &b));
    }
    println!("copied out of the block: {}", result);
    let text = String::from("turbine seven needs service");
    let w = first_word(&text);
    println!("first word: {:?} (borrowed from text, length {})", w, w.len());
    let data = String::from("T07,12.5,north");
    let st = Station { line: &data };
    println!("station id {} | field 1 {:?} | field 5 {:?}", st.id(), st.field(1), st.field(5));
    let fixed: &'static str = "a literal lives for the whole program";
    println!("{} ({} bytes)", fixed, fixed.len());
}
inside the block: North ridge
copied out of the block: North ridge
first word: "turbine" (borrowed from text, length 7)
station id T07 | field 1 Some("12.5") | field 5 None
a literal lives for the whole program (37 bytes)
fn longer(a: &str, b: &str) -> &str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    println!("{}", longer("North ridge", "Bay"));
}
error[E0106]: missing lifetime specifier
 --> m.rs:1:32
  |
1 | fn longer(a: &str, b: &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 `a` or `b`
help: consider introducing a named lifetime parameter
  |
1 | fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
  |          ++++     ++          ++          ++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0106`.
fn main() {
    let result;
    {
        let short_lived = String::from("Bay");
        result = &short_lived;
    }
    println!("{}", result);
}
error[E0597]: `short_lived` does not live long enough
 --> m.rs:5:18
  |
4 |         let short_lived = String::from("Bay");
  |             ----------- binding `short_lived` declared here
5 |         result = &short_lived;
  |                  ^^^^^^^^^^^^ borrowed value does not live long enough
6 |     }
  |     - `short_lived` dropped here while still borrowed
7 |     println!("{}", result);
  |                    ------ borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0597`.

The annotated function longer returned “North ridge”, since “North ridge” has 11 characters and “Bay” has 3, and the compiler accepted it because the result is tied to both inputs. Inside the inner block, where both strings exist, the result is fine. The call that copied the result with to_string before the block closed kept a valid string, “North ridge”, and that is the usual cure when a reference would be too short-lived: copy the data out.

first_word needed no annotation, because there is one input reference and the output must come from it, so the compiler applied the elision rule. It returned “turbine”, 7 bytes, borrowed from text without copying. The struct Station holds a reference to a line, so it carries the lifetime parameter ‘a, and its methods return pieces of that same text: id gives “T07”, field 1 gives Some(“12.5”), and field 5, which does not exist, gives None instead of reading past the end. A string literal has the lifetime ‘static, because it is stored in the program itself, and its 37 bytes are valid for as long as the program runs.

The two failing programs show what the annotations prevent. Without them, error E0106 says “missing lifetime specifier”: the function returns a reference, but the signature does not say whether it comes from a or from b, and the compiler suggests adding a named lifetime parameter. The other program tries to keep a reference to short_lived after the block has ended, and error E0597, “short_lived does not live long enough”, points at the line where the value is dropped while still borrowed. This is exactly the dangling pointer that causes use-after-free bugs in C and C++, and Rust reports it at compile time.

Check by hand: “North ridge” is 5 + 1 + 5 = 11 characters and “Bay” is 3, so the longer is “North ridge”. “turbine” has 7 letters. The line “T07,12.5,north” split on commas has three fields, so index 5 does not exist, and nth returns None.

A lifetime annotation does not extend a lifetime

Writing ‘a cannot keep a value alive. It only tells the compiler how the references relate, and the compiler then checks the claim. If the claim is false, the program will not compile.

When in doubt, own the data

If lifetimes make a struct or function hard to write, return a String or store an owned String field. A small copy is cheaper than a hard-to-read design, and you can optimise later.

About this course

Every program in this lesson was compiled with rustc 1.97 (edition 2021) and run while the course was written. Rust releases every six weeks and its compiler messages improve all the time, so check doc.rust-lang.org for the current edition and wording.

Practice

Write a function that returns the longest of three strings with one lifetime parameter. Make a struct that holds two references with different lifetimes and see when you need two names. Try to return a reference to a local String from a function and read the error.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does a lifetime describe?

  1. How fast code runs
  2. A thread
  3. How long a reference is valid
  4. A type

It relates references to data.

Why does fn longer(a: &str, b: &str) -> &str fail?

  1. It is a syntax error
  2. The compiler cannot tell which input the result is tied to
  3. Strings cannot be compared
  4. It is too long

E0106.

What does ‘static mean?

  1. Static typing
  2. Valid for the whole program
  3. A constant function
  4. A global variable only

String literals are ‘static.

What does error E0597 report?

  1. A value does not live long enough
  2. A moved value
  3. Two mutable borrows
  4. A type mismatch

A dangling reference.

When does a struct need a lifetime parameter?

  1. When it holds a reference
  2. Always
  3. Never
  4. When it is public

It must not outlive what it borrows.

Summary

  • A lifetime is the span during which a reference is valid.
  • Annotations describe how references relate; they do not change lifetimes.
  • Structs that hold references need a lifetime parameter.
  • Dangling references are compile errors, not run-time bugs.

Next lesson

Lesson 11 covers closures and more advanced iterators.

Questions

Do I have to write lifetimes all the time?

No. Most code needs none because of elision. They appear for functions that return references from several inputs and for structs that hold references.

What is lifetime elision?

Three rules that let the compiler fill in lifetimes for common patterns, such as one input reference or a &self method.

Can lifetimes cause run-time cost?

No. They exist only at compile time and leave no trace in the program.

Progress is saved in this browser.