Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 132 ยท Ownership and Borrowing

Lifetimes

Understand Rust lifetimes: the 'a syntax, elision rules, structs holding references, multiple lifetimes, 'static, and the errors E0106 and E0597.

Lifetimes have a reputation for being the hardest part of Rust. They are not. The idea fits in one sentence: a reference must never outlive the thing it points to. The compiler already enforces this everywhere; lifetime annotations are only needed in the few places where the compiler cannot work out, on its own, how long a returned or stored reference stays valid.

This lesson builds the idea from scratch. You will see the bug lifetimes prevent, what 'a means (and what it does not do), the three elision rules that make most annotations unnecessary, how to put references in structs, and how to read the errors E0106 and E0597. It follows References and Borrowing and The Borrow Checker in Practice, and Lifetime Patterns and Pitfalls continues from here.

The problem lifetimes solve

Every reference has a lifetime: the part of the program during which it is valid and used. The compiler checks that the lifetime of a reference is never longer than the lifetime of the value it points to. The simplest violation:

Rust A reference that outlives its value (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0597]: `number` does not live long enough
 --> main.rs:5:21
  |
4 |         let number = 42;
  |             ------ binding `number` declared here
5 |         reference = &number;
  |                     ^^^^^^^ borrowed value does not live long enough
6 |     } // `number` is dropped here
  |     - `number` dropped here while still borrowed
7 |
8 |     println!("{reference}");
  |                --------- borrow later used here

In C this compiles, and reference points at a dead stack slot. In Rust the compiler sees that the borrow is used at line 8, after the value dies at line 6, and refuses. Notice that "lifetime" is a compile-time concept: nothing about lifetimes exists at run time, and they cost nothing.

When the compiler needs help

Inside one function the compiler can see everything, so you almost never write lifetimes there. Trouble starts with function signatures. The compiler checks each function in isolation, using only its signature. Consider a function returning one of two strings:

Rust Which input does the result borrow from? (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0106]: missing lifetime specifier
 --> main.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 {
  |          ++++     ++          ++          ++

The returned reference points into either a or b, depending on a run-time comparison. The caller needs to know how long the result stays valid, so the signature must say so. The compiler even suggests the fix.

Lifetime annotations

A lifetime annotation is a name starting with an apostrophe: 'a, 'b, 'input. You declare it in angle brackets after the function name, like a generic type parameter, and attach it to references:

Rust The longer function, annotated

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Read the signature as: "for some lifetime 'a, both inputs are valid for at least 'a, and the result is valid for 'a." In practice, 'a is whatever the overlap of the two inputs' lifetimes is. The result can be used as long as both inputs are still alive.

What annotations do not do:

  • They do not make anything live longer. They only describe relationships so the checker can verify them.
  • They do not change run-time behaviour at all.
  • They are a promise that the function body must keep. If the body returned something that does not satisfy the signature, the compiler would reject the body.

Seeing the overlap

Because the result is tied to both inputs, using it after one input is gone is an error:

Rust The result is tied to the shorter-lived input (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0597]: `inner` does not live long enough

Even though at run time outer is longer and is the one returned, the signature only promises that the result lives as long as the overlap. The compiler judges by signatures, never by guessing which branch will run. If the result really only depends on one input, say so by using two lifetimes (see below) or by annotating only that parameter.

Annotate only what the result depends on

If a function always returns something from its first parameter, give the second parameter a different (or no) lifetime:

Rust Only the first argument is borrowed from

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The result never mentions default's lifetime, so fallback may die first.

Lifetime elision: why you rarely write them

You wrote no lifetimes in fn first_word(text: &str) -> &str. The compiler fills them in using three elision rules, applied in order to function signatures:

  1. Each reference parameter gets its own lifetime. fn f(a: &str, b: &str) becomes fn f<'a, 'b>(a: &'a str, b: &'b str).
  2. If there is exactly one input lifetime, it is assigned to all output references. fn f(a: &str) -> &str becomes fn f<'a>(a: &'a str) -> &'a str.
  3. If one of the inputs is &self or &mut self, its lifetime is assigned to all outputs. That is why methods that return references into self need no annotations.

If, after these rules, an output reference still has no lifetime, you get E0106, the error above. longer fails because it has two inputs and no self.

Rust Elision at work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice that in find, the rule gives the result the lifetime of &self, not of prefix: the book comes from the library, not from the search text. Elision is a convenience that picks the most common meaning; when it picks wrong, you write the annotation yourself.

Structs that hold references

A struct can store a reference, but then it needs a lifetime parameter, because the struct must not outlive the data it borrows:

Rust A struct that borrows its text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Read Excerpt<'a> as "an Excerpt that cannot live longer than whatever 'a is". The impl<'a> Excerpt<'a> repeats the parameter, just like generics. A struct field without a lifetime is rejected:

Rust A reference field without a lifetime (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0106]: missing lifetime specifier
 --> main.rs:2:11
  |
2 |     text: &str,
  |           ^ expected named lifetime parameter
  |
help: consider introducing a named lifetime parameter
  |
1 ~ struct Excerpt<'a> {
2 ~     text: &'a str,
  |

Own or borrow?

Putting a reference into a struct makes the struct dependent on its source: you cannot return it from the function that owns the data, and it infects every type that contains it with a <'a>. Ask whether String (owned) would do instead. Borrowing structs shine for short-lived views and parsers, where avoiding copies matters; owned fields are the better default for long-lived data like configuration, entities and anything sent across threads.

Rust A borrowing struct that cannot escape (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports error[E0515]: cannot return value referencing local variable line``. The fix is to make the token own its word (word: String) or to pass the line in from the caller.

More than one lifetime

When references in a struct or signature are unrelated, give them separate names so the caller is not tied to the shorter of two:

Rust Two independent lifetimes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Descriptive names such as 'text and 'pattern make signatures far easier to read than 'a and 'b. The '_ is an anonymous lifetime meaning "some lifetime I do not need to name"; Lifetime Patterns and Pitfalls says more.

'static

'static is the special lifetime that lasts for the whole program. String literals have it, because their text is baked into the binary:

Rust 'static data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Two things to know:

  • &'static T means "a reference that is valid forever". It is fine for literals and for deliberately leaked data (Box::leak), but you should not add 'static to make a lifetime error go away. If the compiler asks for 'static, it usually means you are trying to send a borrowed value somewhere long-lived (a thread, a global), and the real answer is to make the value owned.
  • T: 'static as a bound (as in thread::spawn) means "T contains no non-static references". Owned types like String and i32 satisfy it, because they hold no borrows at all. Do not confuse "has a 'static bound" with "lives forever".

Reading lifetime errors

Lifetime errors read like a short story. The two to know:

Error Plain meaning Typical fix
E0106 missing lifetime specifier The compiler cannot tell which input a returned (or stored) reference borrows from Add <'a>, tie the right inputs to the output; or return an owned value
E0597 does not live long enough A reference is used after its value was dropped Extend the owner's scope, or move or clone the value, or shorten the use
E0515 cannot return reference to local You return a reference to something created inside the function Return an owned value, or take the data as a parameter
E0499 / E0502 Overlapping mutable borrows (see Borrowing) Shorten one borrow

A practical routine: (1) find which value dies too early, (2) ask whether the reference really needs to outlive it, (3) if yes, extend the owner or return an owned copy; if no, shorten the use.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a lifetime annotation like 'a do at run time?

    Lifetimes are erased after compilation. They describe how long references are valid so the checker can reject dangling references.
  2. 2. Why does fn pick(a: &str, b: &str) -> &str fail with E0106?

    Elision rule 2 applies only with exactly one input lifetime, and rule 3 needs &self. With two inputs the signature must say which one the result is tied to.
  3. 3. What lifetime does the return value get in fn name(&self, key: &str) -> &str under elision?

    Rule 3: when there is a &self parameter, its lifetime is assigned to all output references.
  4. 4. Which struct definition compiles?

    A struct holding a reference needs a lifetime parameter, which it uses on the field.
  5. 5. What does T: 'static as a bound mean?

    The bound says T holds no short-lived borrows. A String satisfies it, and it can still be dropped whenever you like.

Summary

  • A lifetime is the span in which a reference is valid; the rule is that a reference must never outlive its referent. Lifetimes exist only at compile time.
  • Inside a function the compiler infers everything. Signatures need annotations only when an output reference could borrow from several inputs.
  • fn f<'a>(x: &'a T, y: &'a T) -> &'a T ties the result to the overlap of both inputs; unrelated inputs get different or no lifetimes.
  • Elision rules: each reference parameter gets its own lifetime; one input lifetime flows to all outputs; &self flows to all outputs.
  • Structs that hold references need struct S<'a> and impl<'a> S<'a>. Prefer owned fields unless borrowing is the point.
  • 'static means "valid for the whole program" for references (literals, leaked data) and "no short-lived borrows" as a bound. Do not use it to silence errors.
  • Errors: E0106 (missing specifier), E0597 (does not live long enough), E0515 (returning a reference to a local).

Next: Lifetime Patterns and Pitfalls