Sub topic 3
How the borrow checker sees scopes, and non-lexical lifetimes
This chapter assumes you know Rust's ownership rules, the difference between &T and &mut T, and the rule that you may have many shared borrows or one mutable borrow, but not both at once. Here you will learn how the compiler decides how long a borrow lasts. You will also learn why code that looks like it breaks the borrowing rules sometimes compiles.
Scopes are not lifetimes
A scope is a region of source text, usually between { and }. A variable lives until its scope ends, and then Rust drops it. This is a fact about values.
A lifetime is a fact about a reference. It is the part of the program where the reference might still be used. The borrow checker is the compiler pass that checks that every reference is valid for its whole lifetime, and that no conflicting access happens during it.
Early versions of Rust (before 2018) tied the two together. A borrow lasted until the end of the scope that held the reference variable. This was simple to implement, but it rejected correct programs. Modern Rust uses non-lexical lifetimes (NLL). A borrow now lasts from where it is created to its last use.
A borrow lasts until its last use
This program compiles:
fn main() {
let mut scores = vec![10, 20, 30];
let first = &scores[0];
println!("first = {first}");
scores.push(40); // allowed: `first` is never used again
println!("{scores:?}");
}The variable first is still in scope when scores.push(40) runs. Under the old scope-based rule, the shared borrow would still be active, and the mutable borrow needed by push would be an error. NLL looks at use instead. After the println!, nothing reads first, so the borrow is over.
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 immutableOnly the order of statements changed. Now there is a use of first after the push, so the borrow is live when the mutation happens. push might reallocate the vector's buffer, which would leave first pointing at freed memory. The error prevents exactly that.
What the checker actually computes
The compiler turns each function into a control-flow graph. This is a graph of program points with edges for every way execution can move between them. For every reference it computes the set of points where the reference may still be used later. That set is the reference's lifetime.
Two kinds of facts are then checked:
- Outlives constraints. If you write
r = &x, the reference's lifetime must fit inside the timexis alive. The first example in the spine fails here.ris used in theprintln!afterxis dropped, so the borrow would have to outlivex. That gives E0597,xdoes not live long enough. - Conflicts. While a borrow is live, you cannot move or mutate the borrowed place, or take a conflicting borrow. The
pushexample above fails here with E0502.
Lifetimes exist only at compile time. They are erased before code generation, so they cost nothing at runtime.
Control flow matters
Liveness is tracked per path through the function, not per line of text.
fn main() {
let mut data = String::from("abc");
let r = &data;
if r.len() > 2 {
println!("long: {r}");
data.push('!'); // fine: on this path `r` is not used again
} else {
println!("short");
}
data.push('?');
}On the if path, r is last used in the println!, so the push after it is allowed. On the else path, r is not used after r.len(). No path uses r after a mutation, so the program is accepted.
Loops add a wrinkle. A use at the top of a loop body is "later" than a mutation at the bottom, because execution comes back around. A borrow that is read on each iteration stays live across the whole loop, including the mutations inside it.
Two-phase borrows
One more rule explains a common surprise:
fn main() {
let mut v = vec![1, 2, 3];
v.push(v.len()); // compiles
println!("{v:?}");
}v.push(...) needs &mut v, and the argument v.len() needs &v. A plain reading would call this a conflict. Rust treats the mutable borrow as reserved first, and activated only when the call actually happens. During the reservation, shared reads are allowed. This is called a two-phase borrow, and it applies to autoref method calls like this one.
Drop counts as a use
Values with a destructor (a Drop implementation) run code when their scope ends. That code may read the references the value holds, so the end of scope counts as a use of the reference.
struct Guard<'a>(&'a str);
impl Drop for Guard<'_> {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn main() {
let g;
{
let s = String::from("temp");
g = Guard(&s);
} // `s` is dropped here, but `g` is dropped later and reads it
}
// error[E0597]: `s` does not live long enoughIf you delete the Drop implementation, the program compiles. Nothing uses g after the inner block, and dropping a plain struct of references does not touch what they point to. The presence of a destructor changes where the borrow's last use is.
Old rule versus NLL
| Question | Scope-based rule (pre-2018) | Non-lexical lifetimes |
|---|---|---|
| Where does a borrow end? | At the end of the scope holding the reference | After the last use of the reference |
| Is control flow considered? | No | Yes, per path |
| Is `push` after the last read of a borrowed `Vec` accepted? | No | Yes |
| What stays the same? | Values are dropped at scope end | Values are dropped at scope end |
A case NLL still rejects
NLL is not a full proof of memory safety. It is a conservative analysis. A well-known limit is a function that returns a borrow in one branch and mutates in another:
use std::collections::HashMap;
fn get_or_insert(map: &mut HashMap<i32, String>, key: i32) -> &mut String {
match map.get_mut(&key) {
Some(v) => v,
None => {
map.insert(key, String::new());
map.get_mut(&key).unwrap()
}
}
}
// error[E0499]: cannot borrow `*map` as mutable more than once at a timeThe returned reference must live as long as the function's output lifetime. NLL therefore treats the first get_mut borrow as live everywhere that lifetime reaches, including the None arm, even though no reference exists there. The code is actually safe, and a newer analysis called Polonius is designed to accept it. For now, restructure the code. Here the standard library offers a direct fix:
use std::collections::HashMap;
fn get_or_insert(map: &mut HashMap<i32, String>, key: i32) -> &mut String {
map.entry(key).or_default()
}
fn main() {
let mut m = HashMap::new();
get_or_insert(&mut m, 1).push_str("hi");
println!("{m:?}");
}Reading borrow errors with this model
When you get E0502, E0499, or E0597, ask three questions in order:
- Where is the borrow created?
- Where is the last use that the compiler believes is reachable? The error message usually marks it with a label such as "borrow later used here".
- What happens between those two points that conflicts: a mutation, a move, or a value going out of scope?
Then fix whichever side is easiest. You can finish using the reference earlier, reorder statements, copy or clone the data so no borrow is needed, or restructure so that the borrow does not flow into a return value.
Exercise
This program fails to compile with E0502. Without removing any line, which single change makes it compile, and why? fn main() { let mut names = vec![String::from("Ana"), String::from("Bo")]; let first = &names[0]; names.push(String::from("Cy")); println!("{first}"); }
Show answer
Move the println!("{first}"); line above names.push(...). The borrow first then has its last use before the mutation, so under NLL it is no longer live when push needs &mut names. Reordering is the only way to do this without removing a line. Cloning the first name (let first = names[0].clone();) also works, but that changes a line instead of reordering them.
Exercise
A struct Guard<'a>(&'a str) holds a reference to a String declared in an inner block, and the struct is declared outside it. The program compiles when Guard has no Drop implementation and fails with E0597 when it has one. Explain the difference.
Show answer
Without Drop, nothing uses the guard after the inner block, so its borrow of the String ends there, before the String is dropped. With a Drop implementation, the destructor runs at the end of the guard's scope and may read the reference. That makes the end of the outer scope a use, so the borrow must stay live after the String has been dropped, and the compiler reports that it does not live long enough.