A lifetime is the stretch of code where a reference is safe to use. This part reads the errors that mention lifetimes, shows what ‘a says in a function signature, and covers the elision rules, structs that hold references and ‘static.
A reference must never outlive the value it points at. The compiler checks this for every reference, and it usually works out the details on its own. Sometimes, mostly when a function returns a reference, it asks you to write a lifetime like 'a.
This part shows what that 'a means, and what it doesn’t mean. It builds on borrowing from Part 7 and Part 8. Every program here was run on Rust 1.95, and its output is pasted from the run.
Try this first
Read this program and decide what it prints before you scroll down:
fn main() {
let r;
{
let x = 5;
r = &x;
}
println!("r = {r}");
}
It doesn’t compile:
error[E0597]: `x` does not live long enough
--> src/main.rs:5:13
|
4 | let x = 5;
| - binding `x` declared here
5 | r = &x;
| ^^ borrowed value does not live long enough
6 | }
| - `x` dropped here while still borrowed
7 | println!("r = {r}");
| - borrow later used here
x lives inside the inner block. At the } on line 6, the block ends and x is gone. But r still points at it, and line 7 reads through r. In C, this program would compile and read memory that no longer belongs to x. That’s called a dangling reference. Rust refuses to build it.
Read the labels from top to bottom, and they draw time:
- line 4:
xstarts to exist; - line 5:
rborrowsx; - line 6:
xis dropped; - line 7:
ris used, afterxis gone.
That’s two stretches of code: where x is alive, and where the borrow in r is needed. The second sticks out past the first.
Both fixes make the stretches fit: print r inside the block, or move let x = 5; out of the block, so x lives as long as r.
A lifetime is a stretch of code
A lifetime is the part of the program where a reference is valid to use. It starts where the borrow is made. It ends at the last place the reference is used. A value also has a stretch where it’s alive, from its let to the point where it’s dropped (Part 6).
The rule is short: a borrow’s lifetime must fit inside the life of the value it borrows. The borrow checker checks it, the same part of the compiler that enforced “many readers or one writer” in Part 7.
Inside one function, the borrow checker sees everything: where each value is made, dropped and used. It never needs your help there. Functions are where it gets stuck.
A function that returns a reference
This function returns the longer of two strings. It copies nothing. It hands back a reference to one of its inputs:
fn longest(a: &str, b: &str) -> &str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let x = String::from("apple");
let y = String::from("fig");
println!("{}", longest(&x, &y));
}
It prints:
error[E0106]: missing lifetime specifier
--> src/main.rs:1:33
|
1 | fn longest(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 longest<'a>(a: &'a str, b: &'a str) -> &'a str {
| ++++ ++ ++ ++
The first help: line names the problem. The result is a reference, so it points at something the caller passed in. Anything made inside longest would be dropped when it returns. But is it a or b? The function picks at run time, by length.
Why does the compiler care? It checks each function on its own. When it checks the call longest(&x, &y) in main, it doesn’t read the body of longest. It reads only the signature: the name, the parameters and the return type. So the signature has to say how long the result may be used. With plain &str everywhere, it doesn’t. This is deliberate: you can change a function’s body without breaking its callers, as long as the signature stays the same.
What <'a> says
The compiler’s suggestion compiles:
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let a = String::from("watermelon");
let b = String::from("fig");
let result = longest(&a, &b);
println!("longest: {result}");
}
It prints:
longest: watermelon
Read the new signature piece by piece:
<'a>declares a lifetime parameter called'a. The apostrophe marks a lifetime, and short names like'aare the custom. It sits in angle brackets the way theTinVec<T>does (Part 15).a: &'a strandb: &'a strsay: both inputs are borrowed for at least the stretch'a.-> &'a strsays: the result may be used only during'a.
Put together, the signature says: the result lives no longer than the shorter of a and b. At each call, the compiler picks the stretch 'a. It has to fit inside both borrows, so it can be at most as long as the shorter one. Then it checks that every use of the result falls inside it.
What the annotation does not do: it doesn’t make a or b live longer, and it changes nothing when the program runs. It’s a description. It tells the compiler how the output relates to the inputs, so each call can be checked without reading the body.
The bar for result must fit inside the shorter of the two input bars. On top it does. Below, result is used after b is dropped, so the call is rejected.
In words: each bar is a stretch of the program, read left to right. b‘s bar is the shorter one, so 'a, where both inputs are alive, is b‘s bar. On top, result is last used before b is dropped, so it fits. Below, result is still in use after b is gone. The red part has nothing safe to point at, so the compiler rejects the call.
When the result outlives one input
Here’s the bottom panel as code. b now lives in an inner block, and result is printed after the block ends:
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let a = String::from("watermelon");
let result;
{
let b = String::from("fig");
result = longest(&a, &b);
}
println!("longest: {result}");
}
It prints:
error[E0597]: `b` does not live long enough
--> src/main.rs:10:30
|
9 | let b = String::from("fig");
| - binding `b` declared here
10 | result = longest(&a, &b);
| ^^ borrowed value does not live long enough
11 | }
| - `b` dropped here while still borrowed
12 | println!("longest: {result}");
| ------ borrow later used here
It’s the same error as in “Try this first”, with the same four labels. But the compiler never looked inside longest. The signature said the result is tied to b as well as a, so b must stay alive until line 12. It doesn’t.
Now look at the values. a is “watermelon”, so at run time longest would return a reference to a, and printing it would be safe. The compiler still says no. It goes by what the signature promises, not by what one run would do. The signature says “this might be b“, and for other strings it would be.
That’s the price of checking functions one at a time: the compiler sometimes rejects a program that would have been fine, and never accepts one that isn’t. If a result can only come from one input, say so in the signature. The second worked example does that.
Explain it like I’m ten
Two friends, Ana and Ben, each lend you a ball at the park. Each says, “You can keep it until I go home.” Your little brother asks to play with the bigger ball. You don’t know yet which one that is. So the safe thing to promise him is: “You can play with it until the first of Ana and Ben goes home.”
That promise is 'a. Saying it doesn’t make Ana or Ben stay longer. It tells your brother when to stop. If he plays on after Ben leaves, you’ve broken the promise, even if today it was Ana’s ball.
The precise version
'a is a generic lifetime parameter. The signature of longest is a set of constraints: both argument borrows must be valid for all of 'a, and the result may be used only within 'a. At each call, the compiler looks for a region 'a that meets them all. If there is none, you get an error like E0597. Separately, it checks that the body keeps the promise and returns only something valid for 'a. Annotations produce no machine code and don’t extend or shorten anything.
Where the analogy breaks: Ana and Ben go home at a time on a clock. Rust has no clock. Lifetimes are stretches of source code, worked out before the program runs. And a borrow doesn’t end at a fixed time: it ends at the last place the reference is used, not at the closing } of its block.
The three elision rules
Most functions that return a reference don’t need 'a, because the compiler fills in the common cases. This is lifetime elision: the lifetimes are still there, you just don’t write them. The compiler applies three rules, in order:
- Each reference parameter gets its own lifetime.
fn print_both(a: &str, b: &str)is read asfn print_both<'a, 'b>(a: &'a str, b: &'b str). - If there’s exactly one input lifetime, every output reference gets it.
fn first_word(s: &str) -> &stris read asfn first_word<'a>(s: &'a str) -> &'a str. - If one of the inputs is
&selfor&mut self, every output reference gets the lifetime ofself. This is for methods, which Part 10 covers. For now, read&selfas “a borrow of the value the method was called on”.
If the rules leave an output reference without a lifetime, you get E0106, as longest did. It has two input lifetimes after rule 1, so rule 2 doesn’t apply, and it isn’t a method, so rule 3 doesn’t either.
Here’s one example of each:
struct Name {
full: String,
}
impl Name {
// Rule 3: the result borrows from self.
fn first(&self) -> &str {
self.full.split(' ').next().unwrap_or("")
}
}
// Rule 2: one input lifetime, so the result gets it.
fn first_word(s: &str) -> &str {
s.split(' ').next().unwrap_or("")
}
// Rule 1: two inputs, two separate lifetimes, no output reference.
fn print_both(a: &str, b: &str) {
println!("{a} / {b}");
}
fn main() {
let sentence = String::from("hello brave new world");
let word = first_word(&sentence);
println!("first word: {word}");
let name = Name {
full: String::from("Ada Lovelace"),
};
println!("first name: {}", name.first());
print_both(word, name.first());
}
It prints:
first word: hello
first name: Ada
hello / Ada
first_word is the case you’ll write most often. It takes one reference and returns a piece of it. The result can only point into s, so there’s nothing to say. If you write the 'a anyway, clippy asks you to remove it: “the following explicit lifetimes could be elided: ‘a”.
Structs that hold references
A struct can hold a reference, if it says how long that reference must be valid. Part 10 covers structs properly. Here we only need one field:
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago, never mind how long.");
let first = novel.split('.').next().unwrap_or("");
let e = Excerpt { part: first };
println!("excerpt: {}", e.part);
println!("novel is still here: {} bytes", novel.len());
}
It prints:
excerpt: Call me Ishmael
novel is still here: 53 bytes
struct Excerpt<'a> reads: an Excerpt borrows something for a stretch called 'a, and part points into it. So an Excerpt can’t outlive the text it points into. Keep e after novel is dropped, and you get E0597 again. The struct copies no text, so it’s cheap, but it’s tied to novel.
You can’t leave the 'a off. A reference field must name its lifetime, because a struct has no inputs for elision to work from.
‘static and string literals
One lifetime has a built-in name: 'static. A 'static reference can be used for the whole run of the program. Every string literal is a &'static str:
fn greeting() -> &'static str {
"hello"
}
fn main() {
let fixed: &'static str = "this text is stored in the program itself";
println!("{} / {fixed}", greeting());
}
It prints:
hello / this text is stored in the program itself
The bytes of "hello" are part of the compiled program file. They’re loaded when it starts and never dropped. So greeting can return a reference to them with no inputs at all. Noisy in Part 6 held a &'static str for the same reason.
If a function makes a String and tries to return a reference to it, the compiler’s help: suggests 'static first and an owned value second. Take the second. 'static can’t work, because the String is dropped when the function returns. Return the String itself, and the caller becomes its owner. Part 25 covers more of 'static, including T: 'static.
Worked example: returning a piece of text you just made
You want a function that loads a text and returns its first sentence. A first try, with the text made inside the function:
struct Excerpt<'a> {
part: &'a str,
}
fn load_first_sentence() -> Excerpt<'static> {
let novel = String::from("Call me Ishmael. Some years ago...");
let part = novel.split('.').next().unwrap_or("");
Excerpt { part }
}
fn main() {
let e = load_first_sentence();
println!("{}", e.part);
}
It prints:
error[E0515]: cannot return value referencing local variable `novel`
--> src/main.rs:8:5
|
7 | let part = novel.split('.').next().unwrap_or("");
| ----- `novel` is borrowed here
8 | Excerpt { part }
| ^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
novel is owned by load_first_sentence, so it’s dropped when the function returns, and the Excerpt points into it. Returning it would hand the caller a dangling reference. No annotation can fix this, because none changes when novel is dropped.
There are two fixes. Return owned data, a String, instead of an Excerpt. Or let the caller own the text and pass it in, so the excerpt borrows from something that outlives the call:
struct Excerpt<'a> {
part: &'a str,
}
fn first_sentence(text: &str) -> Excerpt<'_> {
let part = text.split('.').next().unwrap_or("");
Excerpt { part }
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let e = first_sentence(&novel);
println!("{}", e.part);
}
It prints:
Call me Ishmael
'_ is the placeholder lifetime. It means “whatever elision picks”, here the lifetime of text, by rule 2. Plain -> Excerpt also compiles, but with a warning: “hiding a lifetime that’s elided elsewhere is confusing”. The '_ shows the reader that the result borrows from an input.
Worked example: tie the result to the right input
A config file has lines like name = Ana. We want a function that takes one line and a key, and returns the value if the key matches. The value is a piece of the line, so it’s a &str. With two reference inputs, elision can’t help, so we copy longest and put 'a on everything:
fn value_of<'a>(line: &'a str, key: &'a str) -> Option<&'a str> {
let (k, v) = line.split_once('=')?;
if k.trim() == key {
Some(v.trim())
} else {
None
}
}
fn main() {
let config = String::from("name = Ana\ncity = Lisbon");
let mut found = Vec::new();
for wanted in ["Name", "CITY"] {
let key = wanted.to_lowercase();
for line in config.lines() {
if let Some(v) = value_of(line, &key) {
found.push(v);
}
}
}
println!("{found:?}");
}
The keys arrive in mixed case, as a user might type them, so we lowercase each into a new String. split_once splits at the first =, and ? returns None early if there isn’t one (Part 12). if let Some(v) runs its block only when there’s a value; Part 11 covers Option and if let.
It prints:
error[E0597]: `key` does not live long enough
...
14 | let key = wanted.to_lowercase();
| --- binding `key` declared here
15 | for line in config.lines() {
16 | if let Some(v) = value_of(line, &key) {
| ^^^^ borrowed value does not live long enough
...
20 | }
| - `key` dropped here while still borrowed
21 | println!("{found:?}");
| ----- borrow later used here
|
= note: `found` is a collection that stores borrowed references, but `key` does not live long enough to be stored in it
Read it bottom up. Line 21 uses found, which holds values returned by value_of. The signature says those live no longer than key. But key is dropped at the end of each pass of the outer loop, on line 20, and line 21 comes later. The note: says the same in one line.
The values don’t point into key at all. They point into line, which points into config, which lives to the end of main. The signature ties the result to an input it never comes from. So fix the signature, not the caller. Give key no named lifetime, and elision gives it its own:
fn value_of<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let (k, v) = line.split_once('=')?;
if k.trim() == key {
Some(v.trim())
} else {
None
}
}
fn main() {
let config = String::from("name = Ana\ncity = Lisbon");
let mut found = Vec::new();
for wanted in ["Name", "CITY"] {
let key = wanted.to_lowercase();
for line in config.lines() {
if let Some(v) = value_of(line, &key) {
found.push(v);
}
}
}
println!("{found:?}");
}
It prints:
["Ana", "Lisbon"]
Now the signature says the result borrows from line only. key can be dropped whenever it likes. The compiler checks the body against this promise too: if value_of tried to return key, it wouldn’t compile. The habit to keep: put 'a only on the inputs the result can point into.
Tips and traps
'aon every reference by reflex. It compiles inside the function, then fails at a call site with E0597, as invalue_of. Tie the output only to the inputs it can come from.- Adding
'staticto make an error go away. It compiles only if the data really lives for the whole program. For a value made inside a function, it never does. Return an owned value, such as aString, instead. - Thinking an annotation keeps a value alive. No lifetime makes anything live longer. If a value is dropped too early, move its
letto an outer scope, or use the reference sooner. - “does not live long enough” points at the borrow, not the bug. The
^^marks the&, but the fix is usually elsewhere: thedropped hereline or thelater used hereline. Read all four labels before you change anything. - Writing lifetimes elision would add.
fn first_word<'a>(s: &'a str) -> &'a stris correct and noisy. Clippy flags it withneedless_lifetimes. Leave them out when one input or&selfmakes the answer obvious. - A struct with a reference field ties everything to its source. An
Excerptcan’t be returned past theStringit borrows from. If the struct needs to live on its own, give it an ownedStringfield instead.
A lifetime annotation doesn’t change how long anything lives. It tells the compiler how the output relates to the inputs.
Exercises
Exercise 1. Which of these three signatures need a lifetime annotation to compile? Decide using the elision rules, then check.
fn last_word(s: &str) -> &str
fn shorter(a: &str, b: &str) -> &str
fn total_len(a: &str, b: &str) -> usize
Exercise 2. Take the program from “When the result outlives one input”, which fails with E0597 at &b. Make it compile without changing longest. It should print longest: watermelon.
Exercise 3. Without running it, decide whether this function compiles. It returns either its input or a string literal. If it compiles, what lifetime does the result have?
fn label(name: &str) -> &str {
if name.is_empty() { "anonymous" } else { name }
}
Answers
1. Only shorter needs one. last_word has one input lifetime, so rule 2 gives it to the result. total_len returns a usize, not a reference, so there’s no output lifetime to decide. shorter has two input lifetimes and no self, the same as longest:
fn last_word(s: &str) -> &str {
s.split(' ').next_back().unwrap_or("")
}
fn shorter<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() <= b.len() { a } else { b }
}
fn total_len(a: &str, b: &str) -> usize {
a.len() + b.len()
}
fn main() {
println!("{}", last_word("one two three"));
println!("{}", shorter("fig", "apple"));
println!("{}", total_len("fig", "apple"));
}
It prints:
three
fig
8
2. Make result‘s stretch fit inside b‘s. One way is to print inside the block, before b is dropped. The other is to move b out of the block, so it lives as long as result. Here’s the second:
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let a = String::from("watermelon");
let b = String::from("fig");
let result = longest(&a, &b);
println!("longest: {result}");
}
It prints:
longest: watermelon
3. It compiles. There’s one input lifetime, so by rule 2 the result has the lifetime of name. Returning "anonymous" is fine too. It’s a &'static str, valid for the whole program, so it’s certainly valid for as long as name is. A longer lifetime can always be used where a shorter one is expected.
fn label(name: &str) -> &str {
if name.is_empty() { "anonymous" } else { name }
}
fn main() {
let typed = String::new();
let other = String::from("Ana");
println!("{}", label(&typed));
println!("{}", label(&other));
}
It prints:
anonymous
Ana
What’s next
We’ve used structs a few times now, with Part 10 always “coming later”. In Part 10, we’ll build them properly: fields, impl blocks, and the difference between self, &self and &mut self.