Sub topic 10
Interior mutability: mutating through a shared reference
This chapter assumes you know Rust's ownership and borrowing rules, basic structs and methods, and the difference between &T and &mut T.
The rule being bent
Rust's borrow rules say that at any moment you may have either many shared references (&T) or one mutable reference (&mut T), never both. The compiler checks this before the program runs. The check is conservative: it rejects some programs that would be safe, because it cannot prove they are.
Normally, a shared reference means read-only. If you hold a &Visitor, you cannot change its fields. That is usually what you want, but sometimes a value needs to change while many parts of the program hold shared references to it. A cache that fills in on first use is one example. A counter that tracks how often a value was read is another.
Interior mutability is a design pattern where a type lets you change its contents through a &self reference. The type does this safely by hiding the mutation behind a small, controlled API.
A first example
Cell<T> is the simplest such type. It lets you get and set a value through a shared reference.
use std::cell::Cell;
struct Visitor {
name: String,
visits: Cell<u32>,
}
impl Visitor {
fn record(&self) {
self.visits.set(self.visits.get() + 1);
}
}
fn main() {
let v = Visitor {
name: String::from("ana"),
visits: Cell::new(0),
};
let r1 = &v;
let r2 = &v;
r1.record();
r2.record();
println!("{} visited {} times", v.name, v.visits.get());
}The program prints ana visited 2 times. Both r1 and r2 are shared references, and record takes &self, yet the counter changes. If visits were a plain u32, the assignment inside record would not compile.
Why this is still safe
Rust's real safety goal is to prevent two parties from changing or reading data in conflicting ways at the same time. The &/&mut rule is one way to enforce that goal. Interior mutability enforces it differently, inside the type.
The type that provides interior mutability is built on UnsafeCell<T>, the one primitive Rust offers for mutating data behind a shared reference. The standard library wraps it in safe types that each keep a different promise.
Two approaches
| Type | How it stays safe | What happens on misuse |
|---|---|---|
| `Cell<T>` | Values are copied in and out. You never hold a reference to the contents. | Nothing to misuse. |
| `RefCell<T>` | It tracks active borrows while the program runs. | The program panics. |
The following chapters cover RefCell<T> and Cell<T> in detail.
The trade-off
Interior mutability moves some checking from compile time to runtime, or restricts what you can do with the contents. You gain flexibility. You lose a guarantee: with RefCell, a borrow mistake becomes a panic instead of a compile error.
Exercise
In the Visitor example, record takes &self but changes visits. Why does this compile, and why would it fail if visits were a plain u32?
Show answer
Cell<u32> provides set through a shared reference, and it stays safe because it copies values in and out and never hands out a reference to its contents. A plain u32 field can only be assigned through &mut self, so assigning through &self would be a compile error.