Sub topic 3
How the borrow checker sees scopes, and non-lexical lifetimes
This chapter assumes you know ownership, moves, and the rules for &T and &mut T. It also assumes you have seen the dangling reference error E0597 from the previous chapter. Here you will learn how the compiler decides how long a borrow lasts, and why that is shorter than you might expect.
Scopes versus lifetimes
A scope is a region of source text, usually between { and }. A lifetime, in the compiler's model, is the set of program points where a reference may still be used. Early versions of Rust treated these as the same thing. A borrow lasted until the end of the block that contained it. This was called lexical lifetimes.
Modern Rust uses non-lexical lifetimes (NLL). A borrow lasts from the point where the reference is created to the last point where it is used. After that last use, the borrow is over, even if the variable is still in scope.
The check that rejects a dangling reference
Recall the failing program from the previous chapter.
fn main() {
let r;
{
let x = 5;
r = &x;
} // x is dropped here
println!("{r}");
}
// error[E0597]: `x` does not live long enoughThe compiler reasons in two steps:
- The borrow
&xmust stay alive until its last use, which is theprintln!after the inner block. - The value
xis dropped at the closing brace of the inner block, which is before that use.
The borrow would outlive the data it points to, so the program is rejected. The check compares where the borrow must be alive with where the owner is alive.
NLL in practice
NLL lets code compile when a reference is no longer used, even though it is still in scope.
fn main() {
let mut scores = vec![10, 20, 30];
let first = &scores[0];
println!("first = {first}");
scores.push(40);
println!("{scores:?}");
}The shared borrow first is last used in the first println!. The mutable borrow needed by push starts after that, so the two never overlap. Under the old lexical rules this program failed, because first stayed in scope until the end of main.
Now move the use of first to the end.
fn main() {
let mut scores = vec![10, 20, 30];
let first = &scores[0];
scores.push(40);
println!("first = {first}");
}
// error[E0502]: cannot borrow `scores` as mutable because it is also borrowed as immutableNow the shared borrow is still needed after push, so the two borrows overlap. push can reallocate the vector, which would leave first dangling. The compiler blocks it.
A model of the analysis
NLL works on the control-flow graph of a function, not on the block structure of the source. The compiler records, for each reference, the set of points where it is live. A reference is live at a point if some path from that point leads to a later use. Two borrows conflict only if they are live at the same point and one of them is mutable.
Where NLL does not help
Scope still matters in one place: the owner. A value is dropped at the end of its scope, and NLL does not change that. A borrow can end early, but it can never extend past the owner's drop. Types with a Drop implementation add a wrinkle. The drop itself counts as a use of any references the value holds, so those references must remain valid until the drop runs.
Exercise
In the second scores example, which change makes the program compile without removing any line: moving the println! that uses first above scores.push(40), or declaring first with let mut?
Show answer
Moving the println! above scores.push(40). That ends the shared borrow before the mutable borrow starts. Adding mut to first only allows reassigning the variable and has no effect on the borrow conflict.