Interior mutability
Interior mutability is mutation through a shared reference. Cell, RefCell, Mutex, RwLock, and atomics all wrap an UnsafeCell and reintroduce a safety story the type system can check.
Detailed Explanation
Safe Rust's default is: &T does not write. That default is what lets the compiler treat &T as freely shareable. Some types need to break it in a controlled way. A Mutex must lock and then write through &self. An atomic must increment through &self. The language primitive is UnsafeCell<T>, which says "I may mutate through &. Trust my API." You almost never use UnsafeCell directly.
The safe wrappers split by context. Cell<T> is single-thread, Copy values, get/set with no guard. RefCell<T> is single-thread, runtime borrow flags, guards that panic on conflict. Mutex<T> and RwLock<T> are multi-thread, blocking, poison. Atomics are multi-thread, single words, memory orderings. OnceLock / OnceCell are write-once.
You need interior mutability when the outer type must be shared (&self methods, Arc, a trait object) and something inside must change: a cache, a counter, a lazily initialised field. You do not need it for ordinary &mut self methods on a uniquely owned value.
The cost is the wrapper's contract. A RefCell panic is a logic bug. A Mutex deadlock is a logic bug. An atomic with the wrong ordering is a visibility bug. Interior mutability does not make those go away; it only makes mutation possible through &.
When you reach for it: &self plus a changing cache, or shared ownership plus writes. When you do not: you have &mut self already. Prefer the weakest wrapper that matches the thread story.
Document which fields are interior-mutable and why. A struct that is logically immutable from the outside and caches a HashMap in a Mutex is a normal pattern; a struct that mutates six Cells from &self is an object you can no longer reason about. The wrapper is a privilege. Use it for caches, counters, and once-init, not for the whole domain model.
Code Examples
use std::cell::Cell;
struct Hits {
n: Cell<u32>,
}
impl Hits {
fn bump(&self) {
self.n.set(self.n.get() + 1);
}
}
fn main() {
let hits = Hits { n: Cell::new(0) };
hits.bump();
hits.bump();
println!("{}", hits.n.get()); // prints: 2
}Common Gotchas
`&self` plus mutation needs a wrapper
The compiler will not let you assign a field through `&self` without `Cell`/`RefCell`/`Mutex`/atomics.
Pick the wrapper for the thread model
`RefCell` across threads does not compile. `Mutex` on a single-thread GUI is usually heavier than `RefCell`.
`UnsafeCell` is not a shortcut
It is `unsafe` to get a raw pointer out and write. Use a safe wrapper.
Lazy fields are `OnceLock`
A `Mutex<Option<T>>` works and is more lock traffic than a once-cell for write-once data.