Sub topic 13
Reading lifetime errors and choosing a fix
This chapter assumes you know ownership and moves, &T and &mut T, and the basics of lifetime annotations, elision, structs with references, and impl blocks. It does not introduce new syntax. It teaches you to read the compiler's output and pick the right repair.
Read the error in three parts
Lifetime errors have a consistent shape. Each one gives you three things:
- An error code and a headline. Examples are
E0106(missing lifetime specifier),E0597(does not live long enough), andE0515(cannot return reference to local variable). - Labeled spans. The compiler marks where a value is borrowed, where it is dropped, and where the reference is used later. These three points define the conflict.
- A help line. It often suggests an annotation. Treat that as a hint, not an answer. It fixes the signature, but it does not tell you whether the signature expresses what you mean.
Run rustc --explain E0597 (or cargo with the same code) for a longer explanation of any code.
E0106: the compiler cannot choose a lifetime
This error means the signature has a reference in the return type 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 inputs and no &self, so elision has no rule to apply. Ask what the returned reference actually borrows from. The body returns either x or y, so the result must be valid as long as both are:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
println!("{}", longest("apple", "fig"));
}The same error appears on structs that hold a reference. You have two fixes, and they are different designs:
| Fix | Code | Choose it when |
|---|---|---|
| Add a lifetime parameter | `struct Parser<'a> { input: &'a str }` | The struct is a short-lived view over data that lives elsewhere. |
| Own the data | `struct Parser { input: String }` | The struct must outlive its source, be stored, or be sent to another thread. |
E0515: returning a reference to a local
fn make_greeting(name: &str) -> &str {
let s = format!("Hello, {name}");
&s
}
// error[E0515]: cannot return reference to local variable `s`Elision ties the output to name, which is fine. The problem is that s is dropped when the function returns. No annotation can fix this, because no caller-supplied lifetime outlives a local. The data must be owned by someone who survives the call, so return it:
fn make_greeting(name: &str) -> String {
format!("Hello, {name}")
}
fn main() {
println!("{}", make_greeting("Ada"));
}Do not reach for 'static or Box::leak here. Returning an owned value is almost always correct.
E0597: the owner is dropped too early
This is the most common lifetime error in application code. Here a result is used after one of its inputs has gone out of scope:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
let a = String::from("long string");
let result;
{
let b = String::from("short");
result = longest(a.as_str(), b.as_str());
} // `b` dropped here
println!("{result}");
}
// error[E0597]: `b` does not live long enoughThe single 'a forces result to be valid only while both a and b are alive. Use the spans to find the three points: the borrow of b, the drop of b, and the later use of result. Then choose one of these fixes:
- Shorten the use. Move the
println!inside the inner block. - Lengthen the owner. Declare
bin the outer scope. - Copy out. Convert the result with
.to_string()before the block ends, if you need it afterward.
The first two fixes change the program's scoping. The third changes the data's ownership. Pick the one that matches the program's intent, not the one that silences the error fastest.
Non-lexical lifetimes matter here. A borrow ends at its last use, not at the closing brace. If result were not used after the block, this program would compile.
"Lifetime may not live long enough"
This error means your signature promises more than the body delivers.
fn pick<'a, 'b>(x: &'a str, _y: &'b str) -> &'a str {
_y
}
// error: lifetime may not live long enoughThe signature says the result borrows from x's region, but the body returns something from y. You have three options, and which one is right depends on what you meant:
- Fix the body. Return
x. - Fix the signature. Change the return type to
&'b strif the result really comes fromy. - Add an outlives bound. Write
'b: 'aifyis known to outlivex's region.
fn pick<'a, 'b: 'a>(x: &'a str, y: &'b str) -> &'a str {
if x.is_empty() { y } else { x }
}
fn main() {
println!("{}", pick("", "fallback"));
}'b: 'a reads "'b outlives 'a". It lets a &'b str be used where a &'a str is needed. It is a promise the caller must satisfy, so add it only when the relationship is real.
Methods that return the wrong lifetime
Elision on methods ties the output to &self, not to the data the struct borrows. That can be stricter than you need.
struct Parser<'a> {
input: &'a str,
}
impl<'a> Parser<'a> {
// Elided: returns &'_ str tied to the borrow of `self`.
fn rest_short(&self) -> &str {
self.input
}
// Explicit: returns a str tied to the original input.
fn rest(&self) -> &'a str {
self.input
}
}
fn main() {
let text = String::from("key=value");
let rest;
{
let p = Parser { input: &text };
rest = p.rest();
let _ = p.rest_short();
}
println!("{rest}");
}This compiles because rest borrows from text, not from p. If you assign p.rest_short() to rest instead, you get E0597 on p, since that result is tied to p itself. When a method hands out pieces of the borrowed input, name 'a in the return type.
Choosing a fix
Habits that save time
- Fix the first error first. Later lifetime errors are often consequences of the first.
- Prefer owned data when unsure. A
Stringfield or a.clone()is cheaper than a design that fights the borrow checker. Optimize later if profiling shows a cost. - Do not add
'staticto make an error disappear. It demands that the data lives for the whole program, and it usually moves the error to the caller. - Use the narrowest relationship. If the result depends on one input, give that input its own lifetime parameter instead of sharing one across all of them.
Exercise
This code fails with E0597 on s. Name two different fixes and say what each changes.
fn firstword<'a>(a: &'a str) -> &'a str {
a.splitwhitespace().next().unwrapor("")
}
fn main() {
let word;
{
let s = String::from("hello world");
word = firstword(&s);
}
println!("{word}");
}
Show answer
Fix 1: move the println! inside the inner block so the use ends before s is dropped (changes scope of the use). Fix 2: declare s before the block so it outlives word (changes scope of the owner). A third option is to set word = first_word(&s).to_string(); and make word a String, which copies the data so it no longer borrows from s (changes ownership).
Exercise
A function fn tag(name: &str) -> &str builds a new String and tries to return &new_string. The compiler reports E0515. Why can't a lifetime annotation fix it, and what should the return type be?
Show answer
The new String is a local that is dropped when the function returns, so no lifetime that a caller can supply is long enough. The data must be owned by something that survives the call. Change the return type to String and return the value itself.