skip to content

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%

answer

  1. not only about threads
  2. a loop over a Vec while pushing
  3. two parameters cannot overlap
  4. noalias for the optimiser

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.

solid answer

~40 s

The hazard is not concurrency, it is a write through one path breaking an assumption held by another. Pushing to a `Vec` while a `for` loop iterates over `&v` could reallocate the buffer the iterator points into, so rustc rejects it (E0502) and suggests an index loop or collecting changes first. The same guarantee lets a function trust its parameters: in `fn compute(input: &u32, output: &mut u32)` the compiler knows `output` cannot alias `input`, so it may keep `*input` in a register across the write, and rustc does mark such parameters `noalias` for LLVM. Across threads the same rule is what makes data races impossible in safe code, with `Send` and `Sync` carrying it over thread boundaries. Interior mutability through `UnsafeCell` is the sanctioned exception.

code

rust · 13 lines
rust
struct Inventory {
    stock: Vec<u32>,
}

fn main() {
    let mut inv = Inventory { stock: vec![3, 5, 2] };
    for &qty in &inv.stock {
        if qty < 4 {
            inv.stock.push(10); // reorder low items
        }
    }
    println!("{:?}", inv.stock);
}

go deeper

for a junior

Recall that the rule applies in single-threaded code and give the loop-and-push example as the reason.

for a middle

Walk through why a Vec push can move the buffer, and show the compute(&x, &mut x) call being rejected at the call site.

for a senior

Explain that rustc emits noalias for reference parameters, what optimisations that unlocks, and why aliasing &mut through raw pointers is undefined behaviour rather than a style issue.

for a principal

Connect the guarantee to review policy: interior mutability and unsafe aliasing trade away compile-time proof, so a team should expect a stated reason whenever either appears.

## The question behind the question Interviewers ask this to see whether a candidate thinks the borrow rules are "for threads". They are not. The rule that a `&mut T` excludes every other reference is about **one path writing while another path relies on what it saw**, and that happens in single-threaded code all the time. Rust's rule, from the Rustonomicon's chapter on references, is short: a reference cannot outlive its referent, and a mutable reference cannot be aliased. Here **aliased** means two pointers or variables reach overlapping memory. Below are the concrete failures that rule prevents and what rustc does with the guarantee. ## Hazard 1: iterator invalidation Consider an inventory whose `stock` is a `Vec<u32>`. A loop walks the stock and, for each low item, pushes a reorder entry: 1. `for &qty in &inv.stock` creates an iterator that holds a shared borrow of the vector's buffer. 2. `inv.stock.push(10)` may need more capacity, which means allocating a new buffer, moving the elements and freeing the old one. 3. The iterator would then point into freed memory. rustc refuses step 2 with E0502 and, on this exact shape, adds a help line: consider using an index-based loop instead, or collecting modifications into a separate collection. No runtime check is involved; the program simply cannot be written in safe Rust. ## Hazard 2: a write that changes what a caller just read The Rustonomicon's aliasing chapter uses this function: ```rust fn compute(input: &u32, output: &mut u32) { if *input > 10 { *output = 1; } if *input > 5 { *output *= 2; } } ``` If `input` and `output` pointed at the same `u32` holding 20, the first write would change `*input` to 1, the second test would fail, and the result would be 1. Rewriting the function to read `*input` once and set `*output = 2` directly would then give a different answer. In Rust that call shape, `compute(&x, &mut x)`, does not compile: rustc reports E0502 at the call site. So the function body may assume the two parameters never overlap. ## What rustc does with the guarantee Because overlap is impossible, the compiler can treat a `&mut T` parameter and a `&T` parameter (without interior mutability) as **non-aliasing**. Compiling `compute` with optimisations and looking at the LLVM IR shows both parameters marked `noalias`. That enables the optimisations the Rustonomicon lists: - keeping a value in a register because no pointer can change its memory; - removing a re-read because nothing wrote in between; - removing a write that is overwritten before anything reads it; - reordering reads and writes that provably do not touch the same place. Most languages with unrestricted pointers cannot assume this without whole-program analysis. In Rust it falls out of the type of each parameter. ## Hazard 3: data races A **data race** is two accesses to the same memory at the same time, at least one a write, without synchronisation. The single-threaded rule already forbids "a writer plus anyone else", so extending it across threads needs only a way to say which references may cross a thread boundary. That is what `Send` and `Sync` do: for example, `&T` is `Send` only when `T` is `Sync`. The details belong to the material on threads; the point is that the thread story is a consequence of the aliasing rule, not its purpose. ## Summary table | Without exclusive `&mut` | What can go wrong | What rustc does instead | |---|---|---| | push while iterating | iterator reads freed buffer | rejects with E0502 and suggests an index loop | | overlapping `&` and `&mut` parameters | a write changes a value just read | rejects the call; optimises assuming no overlap | | shared writes across threads | data race, undefined behaviour | requires `Send` and `Sync` to cross threads | ## The exception and the boundary - **Interior mutability.** `Cell`, `RefCell`, `Mutex` and atomics allow mutation through a `&T`. They are all built on `UnsafeCell`, which tells the compiler that this memory may change behind a shared reference, so the no-alias assumption is dropped for it. - **Unsafe code.** Creating two live `&mut` to one value through raw pointers is undefined behaviour, not a clever workaround; the rules for that are covered with undefined behaviour and Miri. - **Restructuring.** When the rule blocks a design, the usual fixes are to collect changes and apply them after the loop, to work with indices, or to split the borrow; choosing among them is the subject of borrow-checker errors.

  • Does the no-alias assumption still hold for a `&Cell<u32>` parameter?
    No. `Cell` wraps `UnsafeCell`, which tells the compiler that the memory may change behind a shared reference. rustc therefore does not treat the contents as immutable for the duration of the borrow, and code reading through it must expect the value to change between reads.
  • If safe code cannot create aliasing `&mut`, what happens when unsafe code does it with raw pointers?
    It is undefined behaviour, because the optimiser has already relied on `noalias`. The program may appear to work, then miscompile at a higher optimisation level or after an unrelated change. Tools such as Miri exist to detect it.

  • The borrow rules exist only to stop data races between threads.
  • Pushing to a Vec while iterating is fine as long as the loop does not read the new items.
  • rustc checks for overlapping references at run time in debug builds.
  • Wrapping a field in Cell keeps the compiler's no-alias optimisations for it.
  • Two &mut to one value made with unsafe code are fine if no thread is spawned.