Sub topic 10
Interior mutability: mutating through a shared reference
This chapter assumes you know Rust's ownership and borrowing rules, how &T and &mut T differ, and how to define structs with methods. It introduces the idea of interior mutability. The next chapters cover RefCell<T> and Cell<T> in detail.
The rule being bent
Rust's borrowing rules say that at any moment a value has either any number of shared references (&T) or exactly one mutable reference (&mut T). The compiler checks this statically. It rejects code that might break the rule, even when the code would be safe at runtime.
A shared reference normally means read-only access. This code does not compile:
fn main() {
let count = 0;
let r = &count;
// *r += 1; // error: cannot assign to `*r`, which is behind a `&` reference
println!("{r}");
}Most of the time this restriction is what you want. Sometimes it is too strict. Consider a method that takes &self because many callers hold the object at once, but that needs to update a hit counter, a cache, or a log. Making the method take &mut self would force every caller to hold exclusive access.
What interior mutability means
Interior mutability is a design pattern where a type lets you change its contents through a shared reference. The type exposes a &self API, and inside it performs the mutation under rules that it enforces itself.
The aliasing rule does not go away. A type with interior mutability still guarantees that you never get two conflicting accesses to the same data at once. What changes is who checks the guarantee and when. Ordinary references are checked by the compiler. Interior-mutability types are checked by code in the standard library, and some of those checks run while the program executes.
The standard library offers two main tools in std::cell:
| Type | How you mutate | What it checks | Works with |
|---|---|---|---|
| `Cell<T>` | Copy values in and out with `get` and `set`; no reference to the contents is ever handed out | Nothing at runtime, because it never lends a reference | Mostly `Copy` types |
| `RefCell<T>` | Borrow the contents with `borrow` and `borrow_mut` | Borrow state at runtime; a violation panics | Any type |
Both are single-threaded types. They do not implement Sync, so the compiler will not let you share them across threads. The thread-safe counterparts, Mutex and RwLock, are covered in a later chapter.
A first example with Cell
The simplest case is a counter that updates through &self:
use std::cell::Cell;
struct Counter {
hits: Cell<u32>,
}
impl Counter {
fn record(&self) {
self.hits.set(self.hits.get() + 1);
}
}
fn main() {
let counter = Counter { hits: Cell::new(0) };
let a = &counter;
let b = &counter;
a.record();
b.record();
println!("hits = {}", counter.hits.get());
}The program prints hits = 2. Two shared references exist at the same time, and both mutate the counter. Notice that counter is not declared mut. The mutability lives inside the Cell.
This is safe because Cell never lets anyone hold a reference into its contents. get copies the value out, and set writes a new value in. No pointer into the cell can be outstanding when set runs, so there is nothing to invalidate.
A second example with RefCell
Cell is not enough when the contents are not Copy, such as a Vec<String>. For that, use RefCell<T>:
use std::cell::RefCell;
struct Logger {
lines: RefCell<Vec<String>>,
}
impl Logger {
fn log(&self, msg: &str) {
self.lines.borrow_mut().push(msg.to_string());
}
}
fn work(logger: &Logger, n: u32) -> u32 {
logger.log(&format!("work({n})"));
n * 2
}
fn main() {
let logger = Logger {
lines: RefCell::new(Vec::new()),
};
let total = work(&logger, 1) + work(&logger, 2);
println!("total = {total}");
for line in logger.lines.borrow().iter() {
println!("{line}");
}
}The output is:
total = 6
work(1)
work(2)Every function receives &Logger, so no caller needs exclusive access. The log method calls borrow_mut, which returns a guard that gives mutable access to the vector. When the guard is dropped at the end of the statement, the borrow ends.
Where the check moves
With a &mut reference, a conflict is a compile error. With RefCell, the same conflict is detected when the program runs.
Here is the runtime check in action. The try_borrow_mut method reports the conflict as a Result instead of panicking:
use std::cell::RefCell;
fn main() {
let cell = RefCell::new(5);
let first = cell.borrow_mut();
assert!(cell.try_borrow_mut().is_err());
drop(first);
assert!(cell.try_borrow_mut().is_ok());
*cell.borrow_mut() += 1;
println!("value = {}", cell.borrow());
}The program prints value = 6. While first is alive, a second mutable borrow is refused. After drop(first), the cell is free again. Calling borrow_mut instead of try_borrow_mut in the refused case would panic with an "already borrowed" message.
Why the compiler cannot do this for you
A static analysis must reject every program that might violate the rules. It cannot decide some questions, such as whether a borrow will still be alive when a branch executes, so it takes the conservative side. Interior mutability gives you a way to say that you know the access pattern is valid, and to have a runtime check confirm it.
Under the hood, both types are built on UnsafeCell<T>. It is the one primitive that Rust allows to turn a shared reference into a mutable pointer. Cell and RefCell wrap it in safe APIs. You rarely use UnsafeCell directly.
Trade-offs and failure modes
- Panics replace compile errors. A
RefCellbug appears only when the conflicting path runs. Tests that skip that path will not find it. - Small runtime cost.
RefCellstores a borrow counter and updates it on each borrow.Cellhas no such cost. - Hidden state changes. A
&selfmethod that mutates state can surprise readers. Use interior mutability when the mutation is an implementation detail, such as caching, counting, or logging. Do not use it just to avoid writing&mut self. - Not thread-safe. Because
CellandRefCellare notSync, sharing them between threads is a compile error, not a data race. - Guards keep borrows alive. A borrow lasts as long as its guard. Holding a
borrow()guard in a variable while calling code that callsborrow_mut()on the same cell will panic.
Choosing between the two
Use Cell<T> when the value is small and Copy, such as a counter or a flag, and you only need to read and replace it. Use RefCell<T> when you need to look inside or modify a larger value in place, such as pushing onto a Vec. When a value must also have several owners, RefCell is combined with Rc, which is the subject of a later chapter.
Exercise
A struct has a method fn lookup(&self, key: u32) -> u32 that computes a result and stores it in a HashMap<u32, u32> field so repeated calls are fast. The method must keep taking &self. Which interior-mutability type fits the field, Cell or RefCell, and what happens if lookup calls itself recursively while holding a borrow_mut() guard?
Show answer
Use RefCell<HashMap<u32, u32>>, because the map is not Copy and needs in-place modification. If a recursive call tries borrow_mut() (or borrow()) on the same cell while the outer guard is still alive, the borrow rules are violated and the program panics at runtime. The fix is to end the guard before recursing, for example by checking the map in one short statement, releasing the borrow, computing the result, then borrowing again to insert.