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?
answer
- many readers or one writer
- aliasing XOR mutation
- one is Copy, the other is not
- a borrow ends at its last use
basics
~20 sA &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.
solid answer
~50 s`&T` is a shared reference: you read through it, any number may exist at once, and it is `Copy`. `&mut T` is an exclusive reference: you can mutate through it, and while it is in use nothing else may touch the value, not another `&mut`, not a `&`, not even the owner. That rule is often summarised as aliasing XOR mutation: a value can be shared or mutated, never both at the same moment. rustc checks it at compile time, and since non-lexical lifetimes a borrow lasts only until its last use, so a finished shared borrow does not block a later `&mut`. The payoff is that code holding a `&T` can rely on the value not changing underneath it (interior-mutability types such as `Cell` are the deliberate exception), which rules out data races and iterator invalidation at no runtime cost.
code
rust · 20 linesstruct Inventory {
stock: Vec<u32>,
}
fn total(inv: &Inventory) -> u32 {
inv.stock.iter().sum()
}
fn restock(inv: &mut Inventory, qty: u32) {
inv.stock.push(qty);
}
fn main() {
let mut inv = Inventory { stock: vec![3, 5] };
let report = &inv;
let audit = &inv; // many shared borrows at once: fine
println!("{} {}", total(report), total(audit));
restock(&mut inv, 7); // report and audit are not used again
println!("{}", total(&inv));
}go deeper
Recall the rule exactly: many &T or one &mut T, never both, and that the owner is restricted too while a borrow is live. Know that &mut needs a let mut binding.
Explain that borrows end at their last use under non-lexical lifetimes, and why &T is Copy while &mut T is not. Show which line to move to fix the conflict.
Tie the rule to what it prevents, data races, iterator invalidation and stale reads across a call, and name interior mutability as the one sanctioned exception with its own costs.
Frame aliasing XOR mutation as an API design tool: a signature taking &mut self promises exclusive access, so choose receivers that state what a method really needs rather than defaulting to &mut.
## Two kinds of reference A **reference** in Rust is a pointer that borrows a value someone else owns. There are exactly two kinds, and the difference between them is not just "read" versus "write". It is **shared** versus **exclusive**. | | `&T` (shared reference) | `&mut T` (mutable, exclusive reference) | |---|---|---| | What you may do through it | read | read and write | | How many may be in use at once | any number | exactly one, and no `&T` beside it | | Is it `Copy`? | yes, copying duplicates a pointer | no | | What borrowing a local needs | nothing special | the binding must be declared `let mut` | | What the owner may do meanwhile | read, but not assign or move | nothing until the borrow ends | Take an inventory system: reporting code reads stock through `&Inventory`, while the restock path needs `&mut Inventory`. Two reports can run off the same value at once. A restock must have the value to itself. ## The rule: shared or exclusive, never both The Rustonomicon states the whole model in two lines: a reference cannot outlive its referent, and a mutable reference cannot be aliased. In practice that means, for any one value at any one point in the program: - **any number of `&T`** may be in use, or - **exactly one `&mut T`** may be in use, - **but never both**, and never two `&mut T`. This is often called **aliasing XOR mutation**. "Aliasing" means two paths reach the same memory; "mutation" means one of them writes. Rust allows either property alone and refuses the combination. The rule also covers the owner itself. While a `&Inventory` borrow is still going to be used, the owner can still read `inv`, but assigning to `inv.stock` is rejected (E0506) and so is moving `inv` (E0505). While a `&mut Inventory` borrow is still going to be used, even reading `inv` directly is rejected, because a read would be a second path beside the exclusive one. ## What "at once" means: a borrow ends at its last use Since the 2018 edition introduced **non-lexical lifetimes (NLL)**, a borrow is live from where it is created to where it is **last used**, not to the end of the enclosing block. So this compiles: 1. `let report = &inv;` and `let audit = &inv;` create two shared borrows. 2. Both are read in a `println!`, which is their last use. 3. `restock(&mut inv, 7)` then takes an exclusive borrow. Nothing conflicts, because the shared borrows are already over. Move the `println!` of `report` below the `restock` call and the program no longer compiles: the shared borrow is still live when the exclusive one starts, and rustc reports E0502. Reading that error message and choosing a fix is the subject of the lesson on borrow-checker errors; the point here is the rule it enforces. ## Why `&T` is Copy and `&mut T` is not Copying a shared reference just duplicates a pointer. Since many readers are allowed, an extra copy can never break the rule, so `&T` implements `Copy`. The Rust Reference says of `&mut T` that, while it has not been borrowed from, it is the only way to access the value it points to, "so is not Copy". If it were `Copy`, one exclusive reference could be turned into two, and the guarantee would be gone. Passing a `&mut T` around therefore either moves it or reborrows it for a shorter span. ## What the rule buys Because a `&T` holder knows nobody can write while it reads, and a `&mut T` holder knows nobody else can see the value while it writes: - **No data races.** A race needs two accesses at once with at least one write, and that combination cannot be written in safe code. - **No iterator invalidation.** You cannot push to a `Vec` while a loop is iterating over a shared borrow of it. - **Local reasoning.** A function taking `&Inventory` can read the same field twice and get the same answer. ## The deliberate exception and the common slips **Interior mutability** is the one sanctioned way to mutate through a shared reference: types such as `Cell` and `RefCell` (built on `UnsafeCell`) permit it under their own rules, covered with smart pointers. Outside them, a `&T` means "no writes while I look". Common slips in interviews: - saying two `&mut` borrows are harmless in single-threaded code (the rule is not only about threads; iterator invalidation is a single-threaded bug); - confusing `let mut r = &x;` (the binding `r` can be pointed elsewhere) with `let r = &mut x;` (you can write to `x` through `r`); - saying a borrow lasts until the closing brace, which was the pre-2018 behaviour.
- Can the owner read a value directly while a `&mut` borrow of it is still going to be used?No. A direct read is a second access path beside the exclusive one, so rustc rejects it, for example `println!("{}", inv.stock.len())` between `let r = &mut inv;` and a later `r.stock.push(1)` gives E0502. Once `r` has been used for the last time, the owner is free again.
- What is the difference between `let mut r = &x;` and `let r = &mut x;`?`let mut r = &x;` makes the binding `r` reassignable, so it can later point at another value, but it is still a `&T` and writing `*r = 7` fails with E0594. `let r = &mut x;` creates an exclusive reference you can write through, and it requires `x` itself to be declared `let mut`.
- Why can you pass the same `&T` to several functions but must think about a `&mut T`?`&T` is `Copy`, so each call gets its own copy of the pointer and the original stays usable. `&mut T` is not `Copy`; at a call whose parameter type is `&mut T` the compiler reborrows it for the call, and in other positions, such as a generic `T` parameter, it is moved.
- Two &mut references to one value are fine as long as only one thread runs.
- A shared borrow always lasts until the closing brace of its block.
- Declaring let mut r = &x lets you modify x through r.
- A &T guarantees the value never changes again for the rest of the program.
- The borrow rules are checked at run time and panic when broken.