Mutable references
A mutable reference &mut T is an exclusive borrow. While it lives, nothing else may read or write that T through another path.
Detailed Explanation
&mut T is not "a reference that happens to allow writes". It is a uniqueness claim. The compiler uses that claim to optimise (no other alias) and to keep you from invalidating pointers (no push on a Vec while an element reference exists). let r = &mut v; let s = &mut v; does not compile if r is still live.
You obtain one with &mut value, and value itself must be mut. let x = 1; let r = &mut x; is an error. let mut x = 1; is the binding that may be mutably borrowed. A function that takes &mut self mutably borrows the whole receiver for the call.
Reborrowing is how nested calls work. Passing &mut *r or just &mut *guard creates a shorter mutable borrow. While the callee holds it, you cannot use r. When the callee returns, r is usable again. NLL makes this mostly automatic.
&mut T is not Copy. You cannot have two &mut copies. You can reborrow. You can std::mem::replace or std::mem::swap to work with two pieces of the same value. split_at_mut exists because two &mut into one slice are allowed when the compiler sees they do not overlap.
When you write &mut T: you will modify the value and the caller should see the change. When you take T by value: you want to consume it. When you want shared mutation on one thread: RefCell. Across threads: Mutex.
Splitting a mutable borrow is the skill that replaces C's two pointers into one buffer. split_at_mut, split_first_mut, and iter_mut exist so you do not write unsafe. If you cannot name a safe split, the two writes probably alias and the checker is right. Redesign the data into two collections or two indices plus one slice.
Code Examples
fn bump(n: &mut i32) {
*n += 1;
}
fn main() {
let mut n = 1;
bump(&mut n);
bump(&mut n);
println!("{n}"); // prints: 3
}Common Gotchas
Two live `&mut` to the same value will not compile
This is not a style warning. End the first borrow before the second, or split the data.
The binding must be `mut`
`let x = vec![]; x.push(1)` fails because `x` is immutable. Write `let mut x`.
`&mut T` is not `Copy`
Passing it to a function that takes `&mut T` reborrows. Passing it to a function that takes `&mut T` by a longer lifetime can consume the exclusive access for that lifetime.
A long-lived `&mut` in a struct freezes the owner
While the struct exists, nobody else can borrow the inner value. Store the owner, not the mutable reference, if you can.