Sub topic 2
Why lifetimes exist: preventing dangling references
This chapter assumes you know basic Rust syntax, ownership and moves, the rules for &T and &mut T, and the difference between String and &str. It explains the problem lifetimes solve. The next chapters cover how to write annotations.
The problem: a reference outliving its data
A reference is an address. If the value at that address is destroyed, the address is a dangling reference: it still looks like a pointer, but it points at memory that has been freed or reused.
In languages with manual memory management, such as C, this is a classic bug. The program reads freed memory and may crash, return garbage, or expose data from another part of the program. Garbage-collected languages avoid it by keeping an object alive as long as anything refers to it. Rust has no garbage collector. It frees a value at a fixed point, when its owner goes out of scope. So Rust must prove, before the program runs, that no reference is used after that point.
Lifetimes are the compiler's tool for that proof.
The canonical failing example
fn main() {
let r;
{
let x = 5;
r = &x;
} // x is dropped here
println!("{r}");
}
// error[E0597]: `x` does not live long enoughFollow the program step by step:
ris declared in the outer scope. It has no value yet.- Inside the inner block,
xis created andris set to point at it. - The block ends and
xis dropped. Its storage is no longer valid. println!usesr, which would now read through a dangling pointer.
The compiler reports E0597, "x does not live long enough". It adds notes that x is dropped while still borrowed and that the borrow is later used. Those notes mark the three events that matter: where the borrow starts, where the owner dies, and where the borrow is used afterward.
The value 5 is an i32, which is Copy. That does not help. &x borrows the variable x, not a copy of its contents, so the borrow cannot outlast the variable.
Lifetimes as regions of code
Every reference has a lifetime: the span of the program during which that reference may be used. Every value also has a span during which it is alive, from its creation to its drop. The rule the compiler enforces is:
> The data a reference points to must be alive for the whole lifetime of the reference.
In the failing example, the lifetime of r has to cover the println! call. The lifetime of x ends at the closing brace of the inner block. The first span is longer than the second, so the compiler rejects the program.
A lifetime is not a runtime value. It does not exist in the compiled program, and it costs nothing to run. It is a piece of information the compiler uses while checking your code. Lifetimes describe relationships that already exist. They do not extend how long a value lives.
The fix: make the owner outlive the borrow
To make the program valid, the owner must outlive every use of the reference. The simplest way is to declare x in the same scope as r, or an outer one.
fn main() {
let x = 5;
let r = &x;
println!("{r}");
}Now x lives until the end of main, and r is last used before that. The borrow sits entirely inside the life of its owner, so the compiler accepts it.
The same bug inside a collection
Dangling references often hide in data structures. Here, a vector holds references, and one of the referents dies early.
fn main() {
let mut names: Vec<&String> = Vec::new();
{
let temp = String::from("short-lived");
names.push(&temp);
} // temp is dropped here
println!("{names:?}");
}
// error[E0597]: `temp` does not live long enoughThe vector names lives in the outer scope, so everything it holds must stay valid that long. The compiler tracks this through the type. Vec<&String> carries a lifetime for its references, and pushing &temp forces that lifetime to be no longer than temp's. The later use of names extends it past temp's drop, which is the contradiction.
There are two usual fixes. Move the owner outward so it lives long enough, or store owned data instead of references:
fn main() {
let mut names: Vec<String> = Vec::new();
{
let temp = String::from("short-lived");
names.push(temp);
}
println!("{names:?}");
}Here push(temp) moves the String into the vector, so the vector owns it and nothing dangles. Choosing between "make the owner live longer" and "own the data instead of borrowing it" is the central decision in lifetime errors.
Returning a reference to a local variable
The most common real-world form of this bug is a function that returns a reference to something it created.
fn make_greeting() -> &String {
let s = String::from("hello");
&s
}
// error[E0106]: missing lifetime specifierThe local s is dropped when the function returns. Any reference to it would dangle as soon as the caller received it.
The compiler's first complaint here is E0106, not a dangling error. The return type &String is a reference, but nothing in the signature says which input it borrows from, and there are no inputs. Compiler help text may suggest 'static. Following that suggestion only moves the failure. With a lifetime named in the signature, the body is then rejected with E0515, "cannot return reference to local variable s". The real fix is to return the owned value:
fn make_greeting() -> String {
String::from("hello")
}Ownership transfers to the caller, who decides how long the string lives.
Why the compiler needs your help for functions
Inside one function, the compiler can see every scope and every drop, so it works out lifetimes without any annotations. That is why the examples above use none.
Across a function boundary it cannot see inside the callee when checking a caller. It checks each function separately. It checks the body against the signature, then checks callers against the signature alone. So when a function returns a reference, the signature must say how the returned reference relates to the arguments. If the signature leaves that open, the compiler cannot verify callers, and it asks you to state the relationship.
For some signatures the relationship is obvious and the compiler fills it in for you. That is lifetime elision, covered later. Where it is ambiguous, you write annotations. Annotations describe a relationship the code must satisfy. They never change how long any value lives.
What the compiler guarantees
The guarantee is one-directional. If your program compiles, no safe code can use a reference after its referent is dropped. The reverse does not hold. Some programs are perfectly safe but rejected, because the checker works from signatures and scopes and cannot always see why a use is valid. In those cases you restructure the code or adjust the annotations.
In summary:
| Situation | What goes wrong | Typical fix |
|---|---|---|
| Reference used after its owner's block ends | E0597, owner dropped while borrowed | Declare the owner in an outer scope |
| Reference stored in a longer-lived collection | E0597, referent dies first | Move the owner outward, or store owned values |
| Function returns a reference with nothing to borrow from | E0106, then E0515 if forced | Return an owned value |
Exercise
The following program fails with E0597. Explain which value is dropped too early, and give two different fixes. fn main() { let longest; { let a = String::from("abc"); longest = a.as_str(); } println!("{longest}"); }
Show answer
The String a is dropped at the closing brace of the inner block, while longest still borrows from it and is used afterward in println!. Fix 1: declare a before the inner block, in the same scope as longest, so it lives until the end of main. Fix 2: make longest own the data by writing longest = a.clone(); or longest = a; with longest typed as String, so no borrow remains.
Exercise
Why does fn make() -> &String { let s = String::from("x"); &s } fail to compile, and what is the simplest correct version?
Show answer
The function returns a reference, but the signature gives no input to borrow from (E0106). Even with a lifetime written in, s is dropped when the function returns, so returning &s would dangle (E0515). The simplest correct version returns the owned value: fn make() -> String { String::from("x") }.