Sub topic 9
Fixing lifetime errors
This chapter assumes you can read a rustc diagnostic, know what a reference is, and have seen the borrow checker reject code in the earlier chapters. It covers the two lifetime errors you will meet first: E0106 (missing lifetime specifier) and E0597 (borrowed value does not live long enough).
What a lifetime is
A lifetime is the span of code during which a reference is valid. Most of the time the compiler works lifetimes out on its own. It asks for your help only when it cannot tell how long a returned reference stays valid.
Lifetime annotations do not change how long any value lives. They describe a relationship that the compiler then checks.
E0106: missing lifetime specifier
A function that takes two references and returns one leaves the compiler unable to decide which input the result borrows from.
fn longest(a: &str, b: &str) -> &str {
if a.len() >= b.len() { a } else { b }
}rustc reports E0106: missing lifetime specifier. It points at the &str in the return type. A help line says the signature does not say whether the value is borrowed from a or b, and it suggests a named lifetime parameter.
The fix names one lifetime and ties both inputs and the output to it:
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
println!("{}", longest("tutorial", "rust"));
}Read 'a as "the result is valid for no longer than the shorter-lived of the two inputs." The annotation makes the promise explicit, and the compiler checks every caller against it.
Why one parameter needs no annotation
With a single reference parameter, the compiler applies its elision rules and gives the output the same lifetime as the input. This is why fn first_word(s: &str) -> &str compiles with no annotation.
E0597: does not live long enough
This error means a reference outlives the value it points to.
fn main() {
let r;
{
let x = 5;
r = &x;
}
println!("{r}");
}rustc reports E0597: x does not live long enough. The labels show three things: where x is borrowed, where x is dropped (the closing brace of the inner block), and where the borrow is used later (the println!).
The diagram shows the order of events.
You have three ways to fix it:
- Move the owner into the same scope as the reference, so
xlives at least as long asr. - Return or store an owned value instead of a reference, for example a
Stringinstead of a&str. - Shorten the use of
rso it ends beforexis dropped.
Here is the first fix:
fn main() {
let x = 5;
let r = &x;
println!("{r}");
}A common cause: returning a reference to a local
fn make() -> &String {
let s = String::from("hi");
&s
}Adding 'a here does not help. s is dropped when make returns, so no lifetime could make the reference valid. Return the owned value instead:
fn make() -> String {
String::from("hi")
}Choosing a fix
| Symptom | Likely cause | Fix |
|---|---|---|
| E0106 on a return type | Several input references, so the source is unclear | Add a named lifetime that links the output to its source |
| E0597 in nested blocks | Owner declared in a shorter scope | Widen the owner's scope |
| E0106 or E0515 on a local | The reference points at a local value | Return an owned value |
Exercise
The function fn pick(a: &str, b: &str) -> &str { a } fails with E0106. Which signature compiles, and why does it express the intent better than giving both inputs the same lifetime?
Show answer
fn pick<'a>(a: &'a str, _b: &str) -> &'a str { a }. The result only ever borrows from a, so only a and the output share 'a. Callers can then drop or change b while still using the result. Using 'a on both inputs would compile too, but it would needlessly restrict callers.
Exercise
In the E0597 example, why does moving println!("{r}"); inside the inner block fix the error?
Show answer
The borrow &x is then last used while x is still alive. The compiler checks the borrow only up to its last use, and that use now comes before x is dropped at the closing brace.