skip to content

Ownership and Borrowing

Every value has one owner, a move transfers it, and a borrow lends it under rules the compiler checks. Interviewers start here because nothing else in Rust makes sense without it.

on this pageshow

explore

questions

page 1 of 2

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 Rust, why can you still use a `Vec2` after `let b = a;`, but not a `Sprite` that holds a `String`?

level: juniorimportance: must knowfreq 80%

basics

~20 s

A Vec2 of two f32 fields implements Copy, so let b = a duplicates its bits and a stays valid. A Sprite owns a String, so it is not Copy: the same line moves it, and a duplicate needs an explicit clone().

open as a page

In Rust, why does calling `conn.drop()` on a pooled connection guard fail to compile, and how do you release it early instead?

level: juniorimportance: must knowfreq 60%

basics

~10 s

rustc rejects conn.drop() with E0040: Drop::drop only borrows the value, so it would stay usable and be dropped again at scope end. Call std::mem::drop(conn) instead; it takes ownership and runs the destructor once, immediately.

open as a page

In Rust, after `let staged = batch;` or `archive(batch)` with a `Vec<String>`, why is `batch` unusable, and how does ownership come back?

level: juniorimportance: must knowfreq 82%

basics

~20 s

A Vec<String> is not Copy, so a let or a by-value call moves it: the new binding becomes the only owner and the old one is deinitialised, so any later use fails with E0382. Ownership comes back only as a return value.

open as a page

Why can a Rust reference never be null or dangling, and how do you return a lookup that may find nothing?

level: juniorimportance: must knowfreq 60%

basics

~20 s

Safe Rust has no way to write a null reference, and rustc rejects any borrow used after its referent is dropped (E0597). A lookup that may find nothing returns Option<&T>, which std guarantees is the same size as &T.

open as a page

In Rust, what is the difference between `&T` and `&mut T`, and why can both never be in use for the same value at once?

level: juniorimportance: must knowfreq 82%

basics

~20 s

A &T is a shared, read-only borrow, and many can coexist; a &mut T is an exclusive borrow that permits mutation, so while it is in use no other path to the value may be used. rustc checks this at compile time.

open as a page

In Rust, why should a read-only function parameter be `&str` rather than `&String`, and `&[T]` rather than `&Vec<T>`?

level: juniorimportance: must knowfreq 78%

basics

~20 s

A &str or &[T] parameter accepts every borrowed form: a &String or &Vec<T> coerces to it for free, and literals, arrays and sub-slices fit too. A &String parameter rejects those and gains almost nothing, since a shared reference cannot grow the String anyway.

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, which types can implement `Copy`, and why does `#[derive(Clone, Copy)]` fail on a struct with a `String` field?

level: middleimportance: must knowfreq 65%

basics

~20 s

A type can be Copy only if every field is Copy and it has no Drop impl: numbers, bool, char, shared references, raw and function pointers, and tuples or arrays of Copy types. A String field is not Copy, so rustc reports E0204.

open as a page

In Rust, what does a `&str` or `&[T]` hold at run time, and why can't a `String` be cleared while its slice is used?

level: middleimportance: must knowfreq 62%

basics

~20 s

A &str or &[T] is a fat pointer: an address into the owner's buffer plus a length, two machine words, so slicing copies nothing. The slice is a shared borrow of its owner, so String::clear is rejected with E0502 while the slice is used.

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 rustc reject a Rust type that derives `Copy` and also implements `Drop`, reporting error E0184?

level: middleimportance: should knowfreq 50%

basics

~20 s

Copy promises that duplicating a value's bytes duplicates the whole value; Drop says the value owns something that must be released once. Silent copies would each run that release, freeing one resource twice, so rustc forbids the pair with E0184.

open as a page

In Rust, in what order are a function's local variables and a struct's fields dropped, and when does the struct's own Drop::drop run?

level: middleimportance: should knowfreq 50%

basics

~20 s

Locals in one scope drop in reverse declaration order; a struct's fields drop in declaration order. A struct's own Drop::drop runs first, while every field is still intact, and the fields are destroyed after it returns.

open as a page

In Rust, why does `let _ = pool.checkout();` release the guard at once while `let _conn = pool.checkout();` holds it until the block ends?

level: middleimportance: should knowfreq 40%

basics

~20 s

The wildcard pattern _ binds nothing, so the returned guard stays a temporary and is dropped at the end of the let statement. _conn is an ordinary variable, dropped at the end of its block; the underscore only silences the unused-variable lint.

open as a page

Why does rustc reject shipping a Rust `Vec<String>` batch from inside a `for` loop with E0382, 'value moved here, in previous iteration of loop'?

level: middleimportance: should knowfreq 52%

basics

~20 s

rustc follows the loop's back edge: moving batch in one iteration leaves it deinitialised when the next iteration uses it. Reassign batch right after the move, create it inside the loop, or leave the loop after moving it.

open as a page

In Rust, why does `match cfg.token { Some(t) => ..., None => ... }` leave that `Option<String>` field unusable, and how do you match without moving?

level: middleimportance: should knowfreq 55%

basics

~20 s

The pattern Some(t) binds t by value, so the String moves out of the Option and cfg.token is partially moved; later use fails with E0382 whichever arm ran. Match on &cfg.token or use cfg.token.as_deref() to borrow instead.

open as a page

In Rust, after `let endpoint = cfg.endpoint;` moves one `String` field out of a `Config` struct, what can you still do with `cfg`?

level: middleimportance: should knowfreq 48%

basics

~20 s

Rust tracks moves per field: cfg's other fields stay readable, borrowable and movable, but any use of cfg as a whole fails with E0382 until the moved field is reassigned. A struct that implements Drop forbids the partial move (E0509).

open as a page

When rustc resolves `inv.total()`, how do auto-referencing and auto-dereferencing make it work for `Inventory`, `&Inventory` and `Box<Inventory>` receivers?

level: middleimportance: should knowfreq 42%

basics

~20 s

For a method call, rustc builds candidate receiver types by repeatedly dereferencing the receiver, adding &T and &mut T after each, and picks the first that has a matching method. So inv.total() becomes Inventory::total(&inv) whatever pointer inv is.

open as a page

In Rust, how can a function pass its `&mut Inventory` parameter to two calls in a row when `&mut T` is not `Copy`?

level: middleimportance: should knowfreq 40%

basics

~20 s

Each call reborrows: where the parameter type is known to be &mut Inventory, the compiler passes a fresh &mut *inv for the call instead of moving inv, so inv is usable afterwards. A generic T parameter moves it instead.

open as a page

In Rust, how do slice patterns like `[first, .., last]` and `[cmd, args @ ..]` match a `&[T]`, and when is such a match exhaustive?

level: middleimportance: should knowfreq 35%

basics

~20 s

Each slice pattern fixes a length: [] is zero, [x] exactly one, [first, .., last] two or more, and [cmd, args @ ..] one or more, binding args to the rest as a subslice. A slice match is exhaustive only when every length, zero included, is covered.

open as a page

In Rust, why do `&mut img[..mid]` and `&mut img[mid..]` held together fail with E0499, and how does `split_at_mut` fix it?

level: middleimportance: should knowfreq 50%

basics

~10 s

Each &mut img[..] calls IndexMut::index_mut(&mut img, ..), so both slices borrow all of img mutably and rustc reports E0499; it never compares index ranges. split_at_mut(mid) borrows once and returns two non-overlapping &mut [T] halves.

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

In Rust, why can calling `.clone()` on a `&T` or a `&str` hand back a reference instead of an owned value, and when is `to_owned` the right call?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Shared references are always Clone, so if T is not Clone, method lookup clones the &T and returns a reference. str cannot be Clone, so clone on a &str gives a &str; to_owned gives the owned form, a String or a Vec.

open as a page

In Rust, why is `std::mem::forget` a safe function, and what does that mean for a type whose soundness depends on its Drop running?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Rust's safety guarantees do not include destructors always running: safe code can already leak through an Rc cycle or std::process::exit. So mem::forget is safe, and unsafe code must stay sound even if a value's Drop never runs.

open as a page

In Rust, why is `batch` unusable after `if overflow { archive(batch); }`, and how does the compiled program know whether to drop `batch` at scope end?

level: seniorimportance: should knowfreq 32%

basics

~20 s

rustc treats a value moved on any path as moved, so a later use fails with E0382 even under if false. Where a local's state is unknown statically, a hidden stack drop flag decides at scope end whether to drop it.

open as a page

Why does Rust forbid a `&mut T` alongside any other reference to the same value even in single-threaded code, and what does that guarantee buy?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Mutation through one path invalidates what another path assumes: a Vec push can reallocate under a live iterator, and a write can change a value a caller just read. Exclusive &mut rules that out and lets rustc optimise assuming no overlap.

open as a page

A Rust CSV parser slices fields with `&line[start..end]` on untrusted input — which inputs make it panic, and how do you make it panic-free?

level: seniorimportance: should knowfreq 42%

basics

~20 s

&line[a..b] panics when b exceeds the length, when a is greater than b, and, on a str, when a or b falls inside a multi-byte character. On untrusted input use line.get(a..b), which returns None instead, or let split and find produce the boundaries.

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

As the lead on a Rust game engine, what code-review rule would you set for `clone()` calls, especially inside the per-frame render loop?

level: principalimportance: should knowfreq 35%

basics

~20 s

Treat clone() on heap-owning types in per-frame code as a review stop: borrow, reuse buffers with clone_from, or make small value types Copy. Outside hot paths, a clone that keeps code simple is fine. Lint the mechanical cases; profile the rest.

open as a page

showing 1–30 of 31