Sub topic 13
Reading lifetime errors and choosing a fix
This chapter assumes you know ownership, borrowing rules, and the lifetime annotation syntax 'a from earlier chapters. Here you learn to read the three most common lifetime errors and pick a fix for each.
Read the error in three parts
Every lifetime error has the same layout. The error code and message name the problem. The labelled source lines show where a borrow starts and where the borrowed value dies. The help: line suggests a fix. Read the labels first, because they show which value is too short-lived.
E0106: missing lifetime specifier
The compiler gives this error when a function returns a reference and elision cannot decide which input it comes from.
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() { x } else { y }
}
// error[E0106]: missing lifetime specifierThere are two input lifetimes and no &self, so the output lifetime is ambiguous. Tell the compiler how the result relates to the inputs:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
println!("{}", longest("long string", "short"));
}If the result really comes from only one input, tie it to that input alone. Use fn first_of<'a, 'b>(x: &'a str, _y: &'b str) -> &'a str. Don't use one shared 'a for everything by habit, because that makes callers' borrows last longer than they need to.
E0597: borrowed value does not live long enough
The borrowed value is dropped while a reference to it is still used later.
fn main() {
let r;
{
let x = 5;
r = &x;
} // x is dropped here
println!("{r}");
}
// error[E0597]: `x` does not live long enoughThe labels point at the &x borrow, the closing brace where x dies, and the later use of r. The fix is to make the owner live at least as long as the reference:
fn main() {
let x = 5;
let r = &x;
println!("{r}");
}E0515: returning a reference to a local
This error looks like E0597 but occurs inside a function.
fn make() -> &'static str {
let s = String::from("hello");
&s
}
// error[E0515]: cannot return reference to local variable `s`No annotation can fix this, because s is destroyed when the function returns. Return the owned value instead:
fn make() -> String {
String::from("hello")
}
fn main() {
println!("{}", make());
}Choosing a fix
Try the fixes in this order:
- Shorten the borrow, or move the owner to a wider scope.
- Add or adjust annotations so they describe what the code actually does.
- Return or store an owned value such as
Stringinstead of&str.
A .clone() costs an allocation, but it is often the right choice when the data is small or the code is not performance-critical.
Common mistakes
| Mistake | Why it fails |
|---|---|
| Adding `'static` to silence an error | It demands data that lives for the whole program, which locals never do. |
| Using one `'a` on every reference | It forces unrelated borrows to be valid together. |
| Expecting annotations to extend a lifetime | They only describe relationships. They never keep a value alive. |
Exercise
A function fn pick(a: &str, b: &str) -> &str fails with E0106, but its body always returns a. What is the best signature?
Show answer
fn pick<'a, 'b>(a: &'a str, _b: &'b str) -> &'a str. The result depends only on a, so tie the output to a's lifetime. The caller can then drop b while still using the result.
Exercise
A function builds a String inside its body and tries to return &s as &str. The compiler reports E0515. Name two fixes.
Show answer
Return the owned String instead. Alternatively, take a &mut String or an output buffer from the caller, so the data lives in the caller's scope.