In Rust, why does `let first = &ids[0];` followed by `ids.push(4)` compile only when `first` is not used after the push?
answer
- borrows are not scopes
- liveness, not the closing brace
- the last use ends the loan
- a Drop impl counts as a use
basics
~20 sUnder non-lexical lifetimes a Rust borrow lasts until the reference's last use, not to the end of its block. If first is not read after ids.push(4), the shared borrow is already over; reading it later makes rustc reject the push with E0502.
solid answer
~50 srustc's borrow checker uses **non-lexical lifetimes (NLL)**: the region a borrow must cover runs from where the reference is created to its last use on every path, not to the closing brace of its scope. `let first = &ids[0];` starts a shared borrow of `ids`, and `ids.push(4)` needs `&mut ids`. If `first` is dead by the push, the two borrows never overlap and the code compiles. Add `println!("{first}")` after the push and the shared borrow has to stay alive across it, so rustc reports E0502 and labels three points: where the immutable borrow occurs, where the mutable borrow occurs, and where the immutable borrow is later used. The trap is a value whose type implements `Drop` and holds the reference: its destructor runs at the end of the scope and may read the borrow, so the borrow lasts that long.
code
rust · 6 linesfn main() {
let mut ids: Vec<u32> = vec![1, 2, 3];
let first = &ids[0];
ids.push(4);
println!("first = {first}");
}go deeper
Recall that a borrow ends at the reference's last use, and be able to point at the E0502 label that says where the borrow is later used.
Explain liveness: why the push would be unsafe while the reference is still needed, and how reordering or copying the value out removes the overlap.
Spot the hidden uses that stretch a borrow, such as a Drop impl, a loop back-edge, a returned reference or a stored reference, and fix the real cause rather than adding blocks.
Use NLL's precision as an argument for small functions with short-lived borrows; code that keeps references alive for long stretches is where borrow errors and redesigns cluster.
## What the check protects A `Vec<u32>` keeps its elements in a heap buffer. `&ids[0]` is a **shared reference** (`&u32`) into that buffer. `ids.push(4)` takes `&mut ids`, and a push may **reallocate**: move every element to a bigger buffer and free the old one. A reference still pointing into the old buffer would dangle. So rustc forbids a `&mut` borrow of `ids` while a shared borrow of it is still needed. The question is what "still needed" means, and that is where **non-lexical lifetimes** come in. ## Lexical scopes versus non-lexical lifetimes The original borrow checker tied a borrow to the **lexical scope** of the reference: once `first` existed, `ids` stayed borrowed until the closing `}`. NLL, which arrived with the 2018 edition and was later turned on for 2015-edition code as well, computes the borrow from **liveness** instead: a reference is live at a point if some later path may still read it. | | Lexical model (pre-NLL) | Non-lexical lifetimes (today) | |---|---|---| | Borrow starts | where the reference is created | where the reference is created | | Borrow ends | the end of the enclosing block | the last point where the reference may still be used | | `let r = &v[0]; v.push(1);` with `r` unused after | rejected | accepted | | Same code with `r` read after the push | rejected | rejected with E0502 | Every edition current rustc compiles uses NLL, so the left-hand column is history; it explains old answers and blog posts that tell you to wrap a borrow in an extra `{ }` block. ## Reading the E0502 report When the reference is used after the push, rustc prints **E0502**, "cannot borrow `ids` as mutable because it is also borrowed as immutable", and marks three spans: 1. **`immutable borrow occurs here`** under `ids` in `&ids[0]`: where the shared borrow begins. 2. **`mutable borrow occurs here`** under `ids.push(4)`: the conflicting request. 3. **`immutable borrow later used here`** under the later read of `first`: the use that keeps the shared borrow alive across the push. The third label is the one to act on. The conflict exists only because of that later use, so the fix is almost always about that line: move it before the mutation, or stop needing a reference there. ## Where a borrow lives longer than it looks NLL ends a borrow at its last use, but some uses are not written out: - **A destructor.** If the reference is stored in a value whose type implements `Drop`, the drop at the end of the scope is a use, because `drop` may read the reference. rustc says so: "immutable borrow might be used here, when `c` is dropped and runs the `Drop` code for type `Cursor`". - **A loop.** A reference created before a loop and read on the next iteration is live across the whole body. - **A return value.** A reference returned from a function must stay valid for the caller, so the borrow it came from covers the rest of the function, and today's checker can extend that even to paths that never return it. - **A stored reference.** Pushing `&ids[0]` into another collection makes the borrow live as long as that collection is used. ## What NLL does not change - **Drop timing.** Values are still destroyed at the end of their scope; NLL changes how long a borrow is considered live, not when anything is freed. - **The rule itself.** One `&mut` or any number of `&` at a time still holds; NLL only measures more precisely where each borrow is in use. - **Every sound program.** Some safe patterns are still rejected, most famously returning a borrow from one branch of a function and mutating the same data in another. ## Fixing it without fighting the checker - **Reorder**: finish every read of `first` before `ids.push(4)`. - **Copy the value out**: `let first = ids[0];` copies the `u32`, so no borrow exists at all; for a non-`Copy` element, decide whether one clone is cheaper than restructuring. - **Re-borrow after mutating**: read `ids[0]` again after the push instead of keeping an old reference. - **End a `Drop` holder early**: call `drop(c)` once you are done with it, so its destructor runs before the mutation. An extra `{ }` block still works, but under NLL it is rarely needed: the block only helps when it ends the last use, which reordering usually achieves more plainly.
- How would you make the Cursor example compile without removing its Drop impl?End the cursor before the mutation: call `drop(c)` after its last read, or move its creation and use into an inner block that closes before `ids.push(4)`. Either way the destructor, which is the hidden use of the borrow, runs before the `&mut` borrow starts.
- Does NLL change when a value is dropped?No. NLL changes how long a borrow is considered live, not when values are destroyed. Locals are still dropped at the end of their scope, which is exactly why a value with a `Drop` impl keeps its borrow alive to the closing brace.
- A borrow always lasts until the closing brace of the block that created it.
- Wrapping every borrow in an extra block is still required in modern Rust.
- Indexing a Vec with ids[0] already borrows it mutably, so this is E0499.
- If the element type is Copy, a reference to it is not a borrow.
- NLL also moves the point where a value with a Drop impl is destroyed.