Sub topic 12
A first look at interior mutability
This chapter assumes you know let, mut, and shared references (&T) from earlier chapters. It gives an overview only. Ownership and borrowing rules get fuller treatment elsewhere.
The idea
So far, mutability has belonged to the binding. If you write let x = 5;, you can't change x. If you write let mut x = 5;, you can.
Some types change this. Interior mutability means a value can be changed through a shared reference (&T) or an immutable binding. The type allows this because it enforces safety itself, instead of leaving the check to the compiler's usual borrow rules.
Here is the smallest example:
use std::cell::Cell;
fn main() {
let counter = Cell::new(1);
counter.set(counter.get() + 1);
println!("{}", counter.get());
}counter is not declared mut, yet set changes its contents. The program prints 2. Mutability here is a property of the type, Cell<i32>, and not only of the binding.
Cell: replace and copy whole values
Cell<T> never hands out a reference to what is inside it. You can only do two things:
getreturns a copy of the value. This requiresT: Copy.setreplaces the value with a new one.
Because nobody can hold a reference to the contents, a set can never invalidate one. That is why this is safe.
The next example shows why this is useful. A function takes a shared reference and still updates the value:
use std::cell::Cell;
fn bump(counter: &Cell<u32>) {
counter.set(counter.get() + 1);
}
fn main() {
let counter = Cell::new(1);
bump(&counter);
bump(&counter);
println!("{}", counter.get());
}This prints 3. Both calls borrow counter immutably, and the compiler accepts that.
RefCell: borrow rules checked at runtime
Many values are not Copy, such as Vec and String. For these, use RefCell<T>. It lets you borrow the contents, but it checks the borrowing rules while the program runs instead of at compile time.
borrow()returns aRef<T>, which acts like&T.borrow_mut()returns aRefMut<T>, which acts like&mut T.- Many
Refvalues may exist at once, or exactly oneRefMut, but not both.
use std::cell::RefCell;
fn main() {
let log = RefCell::new(Vec::new());
log.borrow_mut().push("start");
log.borrow_mut().push("end");
println!("{:?}", log.borrow());
let first = log.borrow();
let second = log.try_borrow_mut();
println!("{}", second.is_err());
println!("{}", first.len());
}The output is:
["start", "end"]
true
2The first two borrow_mut() calls work because each temporary RefMut is dropped at the end of its statement. The later try_borrow_mut() fails because first is still alive. It returns an Err instead of panicking. Calling borrow_mut() there would panic.
Choosing between the tools
Prefer ordinary mut whenever it works. It gives compile-time guarantees and costs nothing at runtime.
| Type | Access to contents | Checked | Typical use |
|---|---|---|---|
| `let mut x` | Direct | Compile time | Most code |
| `Cell<T>` | Copy in, copy out | Not needed | Counters, flags |
| `RefCell<T>` | `Ref` and `RefMut` guards | Runtime | Non-`Copy` data behind shared references |
Common errors
- Runtime panic from
RefCell. Holding aReforRefMutwhile callingborrow_mut()again panics with "already borrowed". Keep guards short-lived, or usetry_borrow_mutwhen a conflict is possible. - Using
Cellwith non-Copytypes.getis not available for them. You can usetakeorreplaceinstead, but you can't peek inside. - Assuming it works across threads.
CellandRefCellare not thread-safe, and the compiler rejects sharing them between threads. Threaded code usesMutexor atomics.
Summary
A mut binding is the default way to change a value. When you can only get a shared reference, Cell replaces whole Copy values and RefCell hands out checked borrows of anything else.
Exercise
In the RefCell example, why does log.try_borrow_mut() return an error, and what would log.borrow_mut() do in the same place?
Show answer
The Ref stored in first is still alive, and a RefCell allows no mutable borrow while a shared borrow exists. try_borrow_mut() reports this by returning an Err. borrow_mut() would panic at runtime with an "already borrowed" error.
Exercise
Which type fits better for a u32 hit counter updated through a & reference, Cell<u32> or RefCell<u32>? Why?
Show answer
Cell<u32> fits better. u32 is Copy, so you only need get and set. That avoids the runtime borrow tracking and the panic risk that RefCell adds.