Sub topic 9
Fixing lifetime errors
This chapter assumes you can read a rustc diagnostic (error code, primary span, labels, help text) and that you know the ownership and borrowing rules behind E0382 and E0502. Lifetime errors are what you get when a reference might outlive the value it points to, or when the compiler can't tell which value a returned reference points to.
What a lifetime is
A lifetime is the region of code during which a reference is valid. Every reference has one, but you rarely write it down. The compiler infers lifetimes inside function bodies. At function signatures it needs help, because it checks each function on its own, without looking at the callers' code.
Lifetime annotations never change how long a value lives. They describe relationships between references, so the compiler can check that those relationships hold. Two errors cover most of what you will see:
| Code | Message | Typical cause |
|---|---|---|
| E0106 | missing lifetime specifier | A signature or struct field has a reference, and the compiler can't tell where it borrows from |
| E0597 | `x` does not live long enough | A reference is used after the value it borrows has been dropped |
| E0515 | cannot return reference to local variable | A function returns a reference to data it owns |
E0106: missing lifetime specifier
This function takes two references and returns one:
fn longest(a: &str, b: &str) -> &str {
if a.len() >= b.len() { a } else { b }
}rustc reports an abridged diagnostic like this:
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`The labels point at both parameters and at the return type. The help text names the problem. The caller needs to know how long the returned reference stays valid, and the signature doesn't say.
Lifetime elision
You usually don't write lifetimes because of three elision rules. The compiler applies them in order:
- Each reference parameter gets its own lifetime.
- If there is exactly one input lifetime, the output gets that lifetime.
- If one parameter is
&selfor&mut self, the output gets the lifetime ofself.
first_word compiles with no annotations because rule 2 applies:
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
println!("{}", first_word("hello world"));
}longest has two input lifetimes and no self, so none of the rules produce an output lifetime. That is when E0106 appears.
Add a lifetime parameter
Declare a lifetime in angle brackets and attach it to the references that are related:
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let first = String::from("a longer string");
let second = String::from("short");
println!("{}", longest(&first, &second));
}Read 'a here as "the returned reference is valid for no longer than the shorter of the two inputs." The compiler enforces this at each call site.
Annotate only what is related
If the result can only come from one parameter, tie it to that parameter alone. The other one stays free:
fn pick_first<'a>(a: &'a str, _b: &str) -> &'a str {
a
}
fn main() {
println!("{}", pick_first("kept", "ignored"));
}Using the same 'a everywhere makes the signature stricter than it needs to be. Callers then have to keep unrelated values alive longer than necessary.
E0597: does not live long enough
The signature for longest is correct, but a caller can still misuse it:
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let first = String::from("a longer string");
let result;
{
let second = String::from("short");
result = longest(first.as_str(), second.as_str());
}
println!("{result}");
}The error reads:
error[E0597]: `second` does not live long enough
|
7 | let second = String::from("short");
| ------ binding `second` declared here
8 | result = longest(first.as_str(), second.as_str());
| ^^^^^^ borrowed value does not live long enough
9 | }
| - `second` dropped here while still borrowed
10| println!("{result}");
| -------- borrow later used hereThe labels show three events in order: where the value is declared, where it is dropped, and where the borrow is used afterward. A fix has to break that sequence, and there are two ways to do it:
- Move the use of
resultinside the inner block, beforesecondis dropped. - Declare
secondin the outer scope so it lives as long asresult.
The simplest case from the spine works the same way:
fn main() {
let x = 5;
let r = &x;
println!("{r}");
}Declaring x in the same scope as r means x is dropped after r's last use.
E0515: returning a reference to a local
A function can't return a reference to something it created, because the value is dropped when the function ends:
fn shout(input: &str) -> &str {
let owned = input.trim().to_uppercase();
&owned
}rustc reports E0515: cannot return reference to local variable 'owned'. Adding 'a to the signature does not help. The data really is gone. The fix is to return the owned value:
fn shout(input: &str) -> String {
input.trim().to_uppercase()
}
fn main() {
println!("{}", shout(" hello "));
}Return a reference only when the data belongs to someone else, such as a parameter.
Structs that hold references
A struct field with a reference type also needs a lifetime, and the compiler reports E0106 if it is missing:
struct Parser<'a> {
input: &'a str,
}
impl<'a> Parser<'a> {
fn new(input: &'a str) -> Self {
Parser { input }
}
fn first_token(&self) -> &'a str {
self.input.split_whitespace().next().unwrap_or("")
}
}
fn main() {
let text = String::from("let x = 1");
let parser = Parser::new(&text);
println!("{}", parser.first_token());
}The struct can't outlive the string it borrows from. Notice that first_token returns &'a str, not &str. With plain &str, elision rule 3 would tie the result to &self. The returned token could then not outlive the borrow of parser, which is more restrictive than needed. Returning &'a str tells callers the token is valid as long as the original text.
If a struct fights you with lifetimes, consider whether it should own its data. A String field removes the lifetime parameter entirely, at the cost of a copy.
Mistakes to avoid
- Reaching for
'static.&'static strmeans the data lives for the whole program. String literals qualify, but local values never do. Writing'staticto silence an error usually moves the error to the caller or to the function body. - Adding lifetimes everywhere. Annotate only when elision fails. Extra lifetimes make signatures harder to read and can over-constrain callers.
- Fixing the annotation when the data is the problem. If the diagnostic says a value is dropped while borrowed (E0597, E0515), look at where the value lives before you edit the signature.
- Confusing lifetime parameters with generics.
'aandTboth go in angle brackets, but'ais checked at compile time and has no runtime representation.
Exercises
Exercise
This signature fails with E0106. Rewrite it so the result borrows only from text, and prefix is not constrained.
fn strip(text: &str, prefix: &str) -> &str {
text.stripprefix(prefix).unwrapor(text)
}
Show answer
fn strip<'a>(text: &'a str, prefix: &str) -> &'a str { text.stripprefix(prefix).unwrapor(text) }
The result comes only from text, so only text and the return type share 'a. prefix keeps its own elided lifetime.
Exercise
A function builds a String with format! and returns &s where s is that string. rustc reports E0515. Why does adding a lifetime parameter not fix it, and what does?
Show answer
s is owned by the function and is dropped when the function returns, so no lifetime can make a reference to it valid for the caller. Return the String itself (change the return type to String and return s), so ownership passes to the caller.