Sub topic 7
Where a Borrow Ends: Non-Lexical Lifetimes
This chapter assumes you know how shared (&T) and mutable (&mut T) references work, and that you know the rule of many readers or one writer. It also assumes you can read a basic compiler error. The question here is narrower: for how many lines does a borrow count as active?
A borrow lasts until its last use
A borrow starts when you create a reference. A common guess is that it ends when the variable holding the reference goes out of scope. Early versions of Rust worked that way, and the scopes they used were called lexical lifetimes. They rejected many safe programs and forced people to add extra { } blocks to end borrows early.
Modern Rust uses non-lexical lifetimes (NLL). A borrow is live from the point where it is created to the last point where the reference, or anything derived from it, might still be used. After that point the borrow is over, even though the variable is still in scope. NLL has been the default in every edition since Rust 1.36.
The rule has a precise form. The compiler works on the control-flow graph of your function, not on the text. At each point in the graph it asks whether a reference could still be used on some path forward from here. If so, the loan it came from is live at that point.
An example the compiler rejects
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{first}");
}This does not compile. The compiler reports error E0502: it cannot borrow v as mutable because it is also borrowed as immutable. The three lines show the problem:
firstborrows fromv, so a loan onvstarts.v.push(4)needs a mutable borrow while that loan is live. It is live because line 4 still usesfirst.println!usesfirst, which keeps the loan alive through line 3.
The rule exists for a real reason. push may have to allocate a bigger buffer and move the elements. After that, first would point into freed memory.
The same borrows in a different order
fn main() {
let mut s = String::from("a");
let r = &s;
println!("{r}");
let m = &mut s;
m.push('b');
println!("{m}");
}This compiles. The shared borrow r is last used in the first println!. After that line the loan is dead, so &mut s conflicts with nothing. Both r and m are still in scope at the same time, which would have been an error under lexical rules. NLL looks at use, not scope.
The diagram shows the order of events.
| Line | Code | Shared loan on `s` live? | Mutable loan on `s` live? |
|---|---|---|---|
| 3 | `let r = &s;` | Yes | No |
| 4 | `println!("{r}");` | Yes (last use) | No |
| 5 | `let m = &mut s;` | No | Yes |
| 6 | `m.push('b');` | No | Yes |
| 7 | `println!("{m}");` | No | Yes (last use) |
Control flow matters
Liveness follows paths through the function, so a borrow can be live on one branch and dead on another.
fn main() {
let mut s = String::from("a");
let r = &s;
if r.len() > 5 {
println!("{r}");
} else {
s.push('b');
}
println!("{s}");
}This compiles. In the then branch r is used again, so the loan is live there. In the else branch nothing uses r afterwards, so the loan is dead and s.push('b') is allowed. The compiler checks each path separately.
Loops add a path that goes backward. A reference used on the next iteration is live across the whole loop body.
fn main() {
let mut data = vec![1, 2, 3];
let saved = &data[0];
for i in 0..3 {
data.push(i);
println!("{saved}");
}
}This does not compile (E0502). Within one iteration, push comes before the use of saved. The next iteration still uses saved after the previous push, so the loan stays live around the back edge of the loop. The mutable borrow in push conflicts with it.
Two-phase borrows
Some calls look as if they need a shared and a mutable borrow of the same value at once.
fn main() {
let mut v = vec![1, 2, 3];
v.push(v.len());
println!("{:?}", v);
}This compiles. A method call with &mut self uses a two-phase borrow. The mutable borrow is first reserved, and during the reservation it acts like a shared borrow. It becomes a true mutable borrow only when the call actually runs. By then v.len() has already finished. This belongs to the NLL design, and it is why v.push(v.len()) works.
Types with destructors extend a borrow
Dropping a value can count as a use. If a type implements Drop, the compiler assumes the destructor may read any references the value holds. The value is dropped at the end of its scope, so the loan stays live until then.
struct Guard<'a>(&'a String);
impl Drop for Guard<'_> {
fn drop(&mut self) {
println!("dropping guard for {}", self.0);
}
}
fn main() {
let mut s = String::from("a");
let g = Guard(&s);
s.push('b');
println!("{}", g.0);
}This does not compile (E0502). g is used on the last line, but even without that line the error would remain. The implicit drop of g at the end of main reads s, so the shared loan lives until then, and s.push('b') conflicts with it. Remove the Drop impl and delete the last println!, and the program compiles, because the loan then ends after Guard(&s).
Standard containers such as Vec<&T> are treated specially. Their destructors are known not to read the references, so a Vec of references does not extend borrows this way. Your own Drop types do not get this treatment.
What NLL does not accept
NLL is still a conservative analysis. One known case is a function that returns a reference on one path and then borrows mutably on another.
use std::collections::HashMap;
fn get_or_insert(map: &mut HashMap<u32, String>, k: u32) -> &String {
if let Some(v) = map.get(&k) {
return v;
}
map.insert(k, String::new());
map.get(&k).unwrap()
}
fn main() {
let mut m = HashMap::new();
println!("{:?}", get_or_insert(&mut m, 1));
}This is rejected by the stable compiler at the time of writing. The error says *map cannot be borrowed as mutable because it is also borrowed as immutable. The returned reference v must live as long as the caller's lifetime '_, and NLL applies that lifetime to the whole function body, including the path where None was returned and no reference exists. A more precise analysis called Polonius is meant to accept this code, but you should not rely on it yet.
The usual fix is to restructure the code so that one borrow is enough.
use std::collections::HashMap;
fn get_or_insert(map: &mut HashMap<u32, String>, k: u32) -> &String {
map.entry(k).or_default()
}
fn main() {
let mut m = HashMap::new();
println!("{:?}", get_or_insert(&mut m, 1));
}The entry API does the lookup and the insert in one mutable borrow. The &mut String it returns coerces to the &String in the return type.
Practical habits
- Read the error as a story of three points: where the loan starts, where the conflicting use happens, and where the loan is used later. The later use is what keeps it alive.
- To end a borrow earlier, stop using the reference earlier. Move the last use above the conflicting call, or copy the data out first. For example,
let n = v[0];copies ani32and holds no loan. - Do not add extra
{ }blocks to end borrows. They are rarely needed now. The exception is a guard type with a destructor, such as aRefCellborrow or a lock guard, where the scope really does decide when it is dropped. - For loops, check whether a reference created before the loop is used inside it. If so, it is live on every iteration.
Exercises
Exercise
This program fails with E0502. Change only the order of the lines so it compiles and prints 3 4.
fn main() {
let mut v = vec![1, 2, 3];
let last = v.last().unwrap();
v.push(4);
println!("{} {}", last, v.len());
}
Show answer
Print or copy last before the push, or compute what you need before mutating. One fix is to read the length after last is no longer needed and dereference early:
fn main() {
let mut v = vec![1, 2, 3];
let last = v.last().unwrap();
v.push(4);
println!("{} {}", last, v.len());
}
Here `v.last().unwrap() copies the i32, so last holds no loan on v. The push is then allowed, and the program prints 3 4`.
Exercise
In the Guard example, the program only compiles if the Drop impl is removed (and the last println! is deleted). Why does having a Drop impl change the result, even when g is never used after s.push('b')?
Show answer
The compiler treats dropping a value as a use of everything the value borrows, because a Drop impl may read its references. g is dropped at the end of main, so the shared loan on s is still live when s.push('b') needs a mutable borrow. Without a Drop impl, the last real use of g is its creation, so the loan ends right away.