skip to content

Borrow Checker Errors

Most Rust learning is reading borrow-checker errors and fixing them without cloning everything. Interviewers hand over code that fails to compile and ask for the fix.

on this pageshow

questions

6

In Rust, why does `let first = &ids[0];` followed by `ids.push(4)` compile only when `first` is not used after the push?

level: juniorimportance: must knowfreq 70%

answer

  1. borrows are not scopes
  2. liveness, not the closing brace
  3. the last use ends the loan
  4. a Drop impl counts as a use

basics

~20 s

Under 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 s

rustc'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 lines
rust
fn main() {
    let mut ids: Vec<u32> = vec![1, 2, 3];
    let first = &ids[0];
    ids.push(4);
    println!("first = {first}");
}

go deeper

for a junior

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.

for a middle

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.

for a senior

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.

for a principal

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.
open as a page

In a Rust graph editor, why does `nodes.push(..)` inside `for node in &nodes` fail with E0502, and how do you fix it without cloning?

level: middleimportance: must knowfreq 72%

basics

~20 s

A for loop over &nodes keeps a shared borrow alive for the whole loop, because its iterator is advanced on every pass, and push needs &mut nodes and may reallocate. Collect the changes and apply them after the loop, or loop over indices.

open as a page

In Rust, what do E0505 and E0506 report, and how do you fix a move or assignment while a borrow is still live?

level: middleimportance: should knowfreq 45%

basics

~20 s

E0505 reports a move out of a value that is still borrowed; E0506 an assignment to one. Either would leave the reference seeing dropped or replaced data. Finish the borrow first, borrow instead of moving, or copy out what you need.

open as a page

Why does stable rustc reject a Rust cache method that returns the hit from `self.cache.get(&id)` early and inserts on a miss, and how do you fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Returning hit makes the shared borrow from get last for the caller's lifetime, and stable rustc's borrow checker extends that borrow over the miss path too, where insert needs &mut. It reports E0502; the entry API or a contains_key check fixes it.

open as a page

In a Rust `&mut self` method, why does `let out = self.pending;` fail with E0507, and when do `mem::take`, `mem::replace` and `mem::swap` fix it?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Moving a field out through &mut self would leave a hole in a struct its owner still uses, so rustc rejects it with E0507. std::mem::take, replace and swap move the old value out and put a valid value back in the same step.

open as a page

When a Rust graph editor keeps fighting the borrow checker, how do you decide whether to restructure around indices or an arena rather than patch with `clone()` or `RefCell`?

level: principalimportance: should knowfreq 35%

basics

~20 s

Patch a local conflict: reorder, narrow a borrow, copy a small value. Restructure when the data is a graph references cannot express: one Vec of nodes linked by Copy ids removes the conflicts but loses compile-time checks on stale ids.

open as a page