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 covers one idea: why the compiler tracks how long a reference stays valid, and what it rejects.
The problem: a reference that outlives its data
A reference is an address. If the value at that address is dropped while the reference still exists, the reference is a dangling reference. Using it in C or C++ is undefined behavior. Rust makes this a compile-time error.
fn main() {
let r;
{
let x = 5;
r = &x;
} // x is dropped here
println!("{r}");
}
// error[E0597]: `x` does not live long enoughThe variable x lives only inside the inner block. At the closing brace, Rust drops it. The reference r still exists in the outer scope and is used afterward. The compiler sees that r would point at freed storage, so it rejects the program.
What a lifetime is
A lifetime is the span of the program during which a reference is valid. Every reference has one, even when you never write it. The compiler checks one rule for every borrow:
- The borrowed value must live at least as long as every use of the reference.
If the value's span is shorter than the reference's span, compilation fails. No check happens at run time, and the generated code is the same as if the lifetimes did not exist.
Two spans for the example above
The error becomes clear when you name the two spans. Call the span of r 'a and the span of x 'b. For r = &x to be valid, 'b must cover 'a. Here it does not.
The last arrow is the problem. The use of r happens after the end of x.
The fix: make the data live longer
You fix this kind of error by moving the owner into a scope that covers every use of the reference.
fn main() {
let x = 5;
let r = &x;
println!("{r}");
}Now x is dropped at the end of main, after the last use of r. The borrow is valid for its whole span.
Why this matters for functions
Inside one function, the compiler can see every scope and check this rule directly. Across function boundaries it cannot see the caller's scopes. A function that returns a reference must say which input the result borrows from. Lifetime annotations, which later chapters cover, are that statement.
Here is a function that cannot compile without help:
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() { x } else { y }
}
// error[E0106]: missing lifetime specifierThe body may return x or y, depending on run-time data. The compiler cannot tell how long the returned reference stays valid, so it asks you to describe it. Error E0106 means "missing lifetime specifier".
Common mistakes
- Returning a reference to a local variable. The local is dropped when the function returns, so the reference would dangle.
- Reading the error as "the compiler is wrong". The error points at a real path where data could be freed too early.
- Thinking a lifetime changes how long a value lives. A lifetime only describes a relationship. It never extends the life of the data.
Summary of the model
| Term | Meaning |
|---|---|
| Owner | The variable that holds the value and drops it at the end of its scope |
| Borrow | A reference to a value, created with `&` or `&mut` |
| Lifetime | The span during which a borrow is valid |
| Dangling reference | A reference used after its value has been dropped |
Exercise
The code below fails to compile. Which variable is dropped too early, and how do you fix it without changing what gets printed? fn main() { let r; { let s = String::from("hi"); r = &s; } println!("{r}"); }
Show answer
The variable s is dropped at the closing brace of the inner block, while r is still used afterward (error E0597). Fix it by declaring s in the outer scope, before the inner block, or by removing the inner block. Then s lives until the end of main, after the last use of r.
Exercise
Why does the compiler reject fn longest(x: &str, y: &str) -> &str with E0106, even though the body looks correct?
Show answer
The returned reference could come from either x or y. The signature does not say which input it borrows from, and the compiler does not infer this from the function body. It needs a lifetime annotation in the signature to know how long the result stays valid for the caller.