Module 13 — Lifetimes
Goal
Annotations that tell the compiler how long references stay valid — the last piece of the borrow checker, and the one that finally makes E0106 readable.
Start here — what this module is really about
This is the last piece of the borrow checker, and the one with the most intimidating syntax for the least underlying complexity. Before any of it: a lifetime annotation does not change how long anything lives. It changes nothing at runtime. It is a description of a relationship that already exists, written down so the compiler can check it.
Here is the situation that requires one. In module 05 you learned that a reference must never outlive the data it points at. The compiler verifies this inside a function by looking at the code. But across a function boundary it cannot look inside — it only has the signature. So:
fn longest(x: &str, y: &str) -> &str { // ❌ E0106
if x.len() > y.len() { x } else { y }
}The compiler's objection is not about the body. It is: a caller receives a reference back — is it borrowed from x or from y? Those may have different lifespans, and whoever calls this needs to know which one constrains the result. The signature does not say, so it is rejected.
The annotation supplies the missing fact:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {Read 'a as a label, not a duration. The signature now says: the returned reference is valid for as long as the shorter-lived of the two inputs. No behaviour changed; a promise was written down, and the compiler can check both sides of it.
The good news is that you write these far less often than the syntax's reputation suggests, because of elision — three mechanical rules that let the compiler fill in the obvious cases, which is why you have not needed one until module 13.
The one sentence to remember: lifetimes describe how long references are already valid, so that function signatures carry enough information for the compiler to check callers.
Learning objectives
- Explain what a lifetime is (and what it is not)
- Annotate functions, structs, methods, and traits with lifetime parameters
- Apply the three lifetime elision rules by hand
- Use
'staticcorrectly and know when it's a red flag - Diagnose E0106, E0597, E0515, E0621
13.1 What a lifetime actually is
A lifetime is the scope for which a reference is valid. Every reference has one; most of the time the compiler infers it and you never see it.
Lifetime annotations do not change how long anything lives. They describe relationships between the lifetimes of references so the compiler can check them. Think of them as generic parameters — but over scopes instead of types.
The problem they solve:
fn main() {
let r;
{
let x = 5;
r = &x;
} // x dropped here
// println!("{r}"); // ❌ E0597: `x` does not live long enough
}The borrow checker compares the lifetime of r (outer scope) with the lifetime of the
data it points at (inner scope), sees that the reference outlives the referent, and
rejects it.
Analogy — the expiry date on the visitor pass
A reference is a visitor pass to a building. A lifetime is the expiry date printed on it. You are not choosing when the building gets demolished — you are stating, in the signature, that this pass cannot outlive that building. Every E0106 is the compiler saying: you handed someone a pass and never said which building it opens.
13.2 Lifetimes in function signatures
This does not compile:
fn longest(x: &str, y: &str) -> &str { // ❌ E0106: missing lifetime specifier
if x.len() > y.len() { x } else { y }
}The compiler's problem isn't the body — it's the signature. A caller needs to know how
long the returned reference is valid, and the signature doesn't say whether it came from
x or y. Annotate:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}Read as: "for some lifetime 'a, given two references that both live at least as long as
'a, the returned reference is valid for 'a." In practice, 'a becomes the shorter
of the two inputs' lifetimes.
fn main() {
let s1 = String::from("long string");
{
let s2 = String::from("short");
let result = longest(s1.as_str(), s2.as_str());
println!("{result}"); // ✅ result used inside s2's scope
}
let result;
{
let s2 = String::from("short");
result = longest(s1.as_str(), s2.as_str());
}
// println!("{result}"); // ❌ E0597: s2 doesn't live long enough
}Only annotate what you actually return. If only x can be returned, say so — and then y
needs no annotation at all:
fn first<'a>(x: &'a str, _y: &str) -> &'a str { x }This is more permissive: callers can now pass a short-lived y.
You cannot return a reference to a local
fn dangle<'a>() -> &'a String {
let s = String::from("hello");
&s // ❌ E0515: cannot return reference to local variable
}No annotation can save this. The fix is to return an owned String. If you find yourself
adding lifetimes to make an error go away, stop and ask whether you should be returning
ownership instead.
Reading a lifetime annotation out loud
Take it apart piece by piece:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str
// ^^^^ declares a lifetime parameter, like <T> declares a type
// ^^^^^^^^^ x is a reference valid for at least 'a
// ^^^^^^^ so is y
// ^^^^^^^ and so is the resultSpoken: "for some lifetime 'a, this function takes two string references that are both valid for at least 'a, and returns one that is valid for exactly 'a."
In practice 'a becomes the shorter of the two inputs' actual lifetimes, because that is the strongest promise that holds for both. Watch it work:
let long = String::from("a long string");
{
let short = String::from("short");
let result = longest(&long, &short);
println!("{result}"); // ✅ both still alive here
} // short dies here
let result = longest(&long, &short); // ❌ short is already goneTwo things follow that resolve most confusion:
- You are not choosing lifetimes. The values' actual scopes are already fixed by where they are declared. You are only describing which references are tied together.
- The error appears at the call site, not the definition. That is the whole benefit: the signature is the contract, so violations are reported where the mistake was made.
If you find yourself adding 'a everywhere to silence errors, stop and ask the real question instead: does this thing need to hold a reference at all, or should it own its data? For most application code the answer is "own it" — return String, not &str. Lifetime annotations are mainly a library-author's tool.
13.3 The three elision rules
You rarely write lifetimes because the compiler applies these rules automatically. Learn them and you'll know exactly when annotation is required.
- Each elided input lifetime gets its own parameter.
fn f(x: &str, y: &str)→fn f<'a, 'b>(x: &'a str, y: &'b str) - If there is exactly one input lifetime, it is assigned to all output lifetimes.
fn f(x: &str) -> &str→fn f<'a>(x: &'a str) -> &'a str - If one of the inputs is
&selfor&mut self, its lifetime is assigned to all output lifetimes.
Worked examples:
fn first_word(s: &str) -> &str // rule 2 applies → OK, no annotation needed
fn longest(x: &str, y: &str) -> &str // rules 1 only → ambiguous → ERROR
impl Foo { fn get(&self, k: &str) -> &str } // rule 3 → output borrows from selfRule 3 is why methods almost never need annotations, and it also means a method returning
&str returns something tied to self, not to the argument. When that's wrong, annotate
explicitly:
impl Parser {
fn extract<'a>(&self, input: &'a str) -> &'a str { &input[1..] }
}Without the annotation, elision would tie the output to &self and the code would fail to
compile at the call site in confusing ways.
The elision rules — why you rarely write any of this
The compiler applies three mechanical rules before complaining. If they determine every lifetime, you write nothing.
- Each input reference gets its own lifetime parameter.
fn f(x: &str, y: &str)is treated asfn f<'a, 'b>(x: &'a str, y: &'b str). - If there is exactly one input lifetime, it is assigned to all outputs.
fn first(s: &str) -> &strneeds no annotation — there is only one possible source. - If one of the inputs is
&selfor&mut self, its lifetime is assigned to all outputs. This is why methods almost never need annotations.
Now longest makes sense: it has two input references and no self, so rules 2 and 3 do not apply, nothing determines the output's lifetime, and the compiler asks you.
The useful reframing: you only write a lifetime annotation when the answer is genuinely ambiguous — which is exactly when a human reader would also have wondered. The syntax is not bureaucracy; it appears precisely where information was missing.
Analogy — the rules that let you stop writing the obvious
Elision is the receptionist filling in the parts of the form that could only have one answer: one visitor, one building, so the pass obviously belongs to that one. You only write lifetimes by hand when the answer genuinely is ambiguous — which is exactly the moment a human reader needed telling too.
13.4 Lifetimes in structs
A struct holding a reference must declare a lifetime:
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first = novel.split('.').next().expect("no .");
let e = Excerpt { part: first };
println!("{}", e.part);
} // `novel` must outlive `e` — checked hereThe annotation means: an Excerpt instance cannot outlive the string slice it holds.
Methods on it:
impl<'a> Excerpt<'a> {
fn level(&self) -> i32 { 3 } // elision rule 3
fn announce(&self, ann: &str) -> &str { // returns &self's lifetime
println!("Attention: {ann}");
self.part
}
}Design note
Structs holding references are the exception, not the rule. They're
great for zero-copy parsers (&'a str views into an input buffer) but they infect every
type that contains them with a lifetime parameter. When in doubt, own your data
(String instead of &'a str) and optimize later.
13.5 'static
'static means the reference is valid for the entire program.
let s: &'static str = "I live in the binary"; // all string literals are 'staticAs a bound, T: 'static means "contains no references with a shorter lifetime" — which
includes all owned types like String and Vec<u8>. It does not mean "lives forever".
fn spawn_task<T: Send + 'static>(value: T) { } // common on thread APIs
spawn_task(String::from("owned")); // ✅ String: 'staticGotcha
If a compiler error suggests adding 'static to fix a lifetime problem,
that is usually the wrong fix. It's telling you the reference doesn't live long enough;
the real fix is usually to restructure ownership or clone, not to promise the value is
immortal.
Analogy — the permanent fixture
'static is not a magic word that makes a borrow last longer; it is a claim that the thing being pointed at is part of the fabric of the building and will be there as long as the programme runs — like text baked into the binary itself. Adding 'static to silence an error is claiming permanence you have not actually arranged.
13.6 Advanced bits you'll meet
Multiple lifetimes
fn parse<'a, 'b>(input: &'a str, delim: &'b str) -> Vec<&'a str> {
input.split(delim).collect() // output borrows input, not delim
}Lifetime bounds
struct Ref<'a, T: 'a>(&'a T); // T must outlive 'a (often inferred nowadays)
fn print_all<'a, T>(items: &'a [T]) where T: std::fmt::Debug + 'a {
for i in items { println!("{i:?}"); }
}Everything together
use std::fmt::Display;
fn longest_with_announcement<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a str
where
T: Display,
{
println!("Announcement! {ann}");
if x.len() > y.len() { x } else { y }
}Generic type parameters, trait bounds, and lifetimes coexist in one signature — lifetimes first, by convention.
Traits with lifetimes
trait Parser<'a> {
fn parse(&self, input: &'a str) -> Option<&'a str>;
}Higher-ranked trait bounds (a taste)
fn apply<F>(f: F) where F: for<'a> Fn(&'a str) -> &'a str {
println!("{}", f("hello"));
}for<'a> means "for every lifetime 'a" — the closure must work with any input
lifetime, not one particular one. You'll mostly meet this in error messages rather than
writing it.
Jargon buster
Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.
| Term | In plain English |
|---|---|
| lifetime | The span during which a reference is valid. |
lifetime parameter 'a | A label naming that span so relationships can be written down. |
| elision | The compiler filling in lifetimes automatically using three rules. |
'static | A lifetime lasting the whole program — string literals, or data leaked deliberately. |
outlives 'a: 'b | "'a lasts at least as long as 'b." |
| dangling reference | A reference to dropped data. What all of this prevents. |
| borrow checker | The compiler pass that verifies every reference's lifetime against its referent's. |
| variance | The rules for when a longer lifetime may be used where a shorter one was expected. Rarely written by hand. |
If you get stuck
The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.
| What you see | What it means | What to do |
|---|---|---|
error[E0106]: missing lifetime specifier | You returned a reference and the compiler cannot tell what it borrows from. | Add <'a> and tie the output to the right input — or return an owned String instead. |
error[E0597]: does not live long enough | A reference would outlive its data. | Move the data to an outer scope, or restructure to return ownership. |
error[E0515]: cannot return reference to local variable | You returned a reference to something created inside the function. | Return the value itself, not a reference to it. The local is destroyed on return. |
error[E0621]: explicit lifetime required | A struct or signature needs a relationship stated. | Follow the help: line — it usually prints the exact signature you need. |
| Lifetime annotations spreading through your codebase | A design smell, not a syntax problem. | Prefer owned data in structs. Store String, not &'a str, unless you have measured a reason not to. |
Now make it stick: work through the drills for this module, then carry on to Module 14 — Closures & Iterators.
