Sub topic 12
A first look at interior mutability
This chapter assumes you know let and mut, shared references (&T) and mutable references (&mut T), and basic structs with methods. It also assumes you can read a simple compiler error. You do not need Rc, threads, or traits beyond Copy.
The rule that interior mutability bends
Earlier chapters showed that a binding is immutable unless you write mut. That is the surface version of a deeper rule about references:
- A
&Tis a shared reference. Many can exist at once, and you cannot change the value through them. - A
&mut Tis an exclusive reference. Only one can exist at a time, and you can change the value through it.
The compiler enforces this at compile time. This code is rejected:
fn main() {
let x = 5;
let r = &x;
// *r = 6; // error[E0594]: cannot assign to `*r`, which is behind a `&` reference
println!("{r}");
}Sometimes this is too strict. A method may need to update a hit counter, a cache, or a log while the caller only holds &self. Rust offers a controlled escape: types that let you change their contents through a shared reference. This is called interior mutability. The mutation happens "inside" a value that looks immutable from outside.
Mutability in Rust is therefore a property of the binding (let mut) and also, in these cases, a property of the type.
Cell: replace the whole value
std::cell::Cell<T> holds a value and lets you read and overwrite it through &self. The simplest case:
use std::cell::Cell;
fn main() {
let counter = Cell::new(1);
counter.set(counter.get() + 1);
println!("{}", counter.get());
}This prints 2. The binding counter is not mut, yet its contents change. set takes &self, not &mut self.
Cell stays safe because it never hands out a reference to the value inside. You can only do whole-value operations:
getreturns a copy of the value. It requiresT: Copy.setoverwrites the value and drops the old one.replaceoverwrites the value and returns the old one.takereturns the value and leavesT::default()behind. It requiresT: Default.
Since no one holds a pointer into the cell, no reference can be left dangling when the value changes. That is why no runtime check is needed.
Cell inside a struct
The usual use is a field that changes while the method signature stays &self:
use std::cell::Cell;
struct Visits {
count: Cell<u32>,
}
impl Visits {
fn new() -> Self {
Visits { count: Cell::new(0) }
}
fn record(&self) {
self.count.set(self.count.get() + 1);
}
}
fn main() {
let visits = Visits::new();
visits.record();
visits.record();
println!("{}", visits.count.get());
}This prints 2. Callers can pass &Visits around freely, and the counter still advances.
Cell with values that are not Copy
get needs Copy, so Cell<String> has no get. Use replace and take instead:
use std::cell::Cell;
fn main() {
let name = Cell::new(String::from("ada"));
let old = name.replace(String::from("grace"));
println!("{old}");
let current = name.take();
println!("{current}");
let empty = name.take();
println!("{:?}", empty);
}The output is ada, then grace, then "". The last line is an empty string because the second take left String::default() in the cell, and the third take returned it.
RefCell: borrow the contents, checked at runtime
Cell cannot give you a reference into its value. std::cell::RefCell<T> can, and it moves the borrowing rules from compile time to runtime.
borrow()returns aRef<T>, which acts like&T.borrow_mut()returns aRefMut<T>, which acts like&mut T.
use std::cell::RefCell;
fn main() {
let log = RefCell::new(Vec::new());
log.borrow_mut().push("start");
log.borrow_mut().push("middle");
println!("{:?}", log.borrow());
println!("{}", log.borrow().len());
}This prints ["start", "middle"] and then 2. Here log is not mut, but push needs &mut Vec, and borrow_mut supplies it.
A RefCell tracks how many Ref and RefMut guards are alive. The rule is the familiar one:
- Any number of
Refguards, or - exactly one
RefMutguard, never both at once.
A guard ends when it is dropped, normally at the end of its scope or statement. If you break the rule, the program does not fail to compile. It panics when it runs.
use std::cell::RefCell;
fn main() {
let data = RefCell::new(5);
let guard = data.borrow_mut();
println!("{}", data.try_borrow().is_err());
drop(guard);
println!("{}", data.try_borrow().is_ok());
}This prints true and then false... no: it prints true then true. While guard is alive, a second borrow fails, so the first line is true. After drop(guard) the borrow succeeds, so the second line is also true. try_borrow and try_borrow_mut return a Result instead of panicking, so you can handle the conflict.
If you call data.borrow_mut() twice while the first guard is alive, the second call panics with a message about the value already being borrowed.
Keeping guards short
Most RefCell panics come from a guard living longer than you expect. A temporary guard in a single statement is dropped at the semicolon. A guard stored in a let variable lives until the end of the block.
use std::cell::RefCell;
fn main() {
let items = RefCell::new(vec![1, 2, 3]);
// Fine: each temporary guard ends at its semicolon.
items.borrow_mut().push(4);
let total: i32 = items.borrow().iter().sum();
println!("{total}");
// Risky: this guard lives to the end of main.
let first = items.borrow();
println!("{}", first[0]);
// items.borrow_mut().push(5); // would panic: `first` is still alive
drop(first);
items.borrow_mut().push(5);
println!("{}", items.borrow().len());
}The output is 10, 1, and 5. If you must keep a guard in a variable, put it in a small inner block or call drop before the next conflicting borrow.
Sharing a RefCell between owners
A RefCell alone is owned by one place. Its most common partner is Rc<T>, a reference-counted pointer that lets several owners share one value. Rc only gives shared access, so wrapping the value in a RefCell lets those owners change it. Other chapters cover Rc properly. This is only a preview:
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let shared = Rc::new(RefCell::new(0));
let other = Rc::clone(&shared);
*other.borrow_mut() += 5;
*shared.borrow_mut() += 1;
println!("{}", shared.borrow());
}This prints 6. Both names point to the same integer.
Choosing between the options
The same choice as a table:
| Approach | Change through `&self`? | Hand out references to the contents? | Where rules are checked | Cost |
|---|---|---|---|---|
| `let mut` or `&mut T` | No, needs exclusive access | Yes | Compile time | None |
| `Cell<T>` | Yes | No, whole-value operations only | Compile time (no references exist) | None at runtime |
| `RefCell<T>` | Yes | Yes, through `Ref` and `RefMut` | Runtime | A borrow counter and possible panic |
Edge cases and common mistakes
- Using
geton a non-Copytype.Cell<String>has noget. Usetake,replace, or switch toRefCell. - Holding a guard across a call that borrows again. A method that holds
borrow_mut()and calls another method that also callsborrow_mut()on the same cell will panic. Release the guard first, or pass the data down as an argument. - Expecting interior mutability to cross threads. Neither
CellnorRefCellisSync, so the compiler refuses to share them between threads. The thread-safe counterparts areMutex,RwLock, and the atomic types such asAtomicU32. - Reaching for it too early. If you are tempted to use
RefCelljust to silence a borrow-checker error, first check whether restructuring the code (splitting a struct, shortening a borrow) removes the problem.
Summary
A shared reference normally forbids mutation. Cell<T> and RefCell<T> allow it inside a value you only hold by &self. Cell works by copying or swapping whole values. RefCell hands out guarded borrows and panics at runtime if the one-writer-or-many-readers rule is broken. Use ordinary mut by default, and treat interior mutability as a deliberate exception.
Exercise
A struct has the field hits: Cell<u32> and the method fn record(&self). Write the body of record so that each call adds one to hits. Then explain why let v = Visits::new(); v.record(); compiles even though v is not declared mut.
Show answer
The body is self.hits.set(self.hits.get() + 1);. It compiles because Cell::set takes &self, and record takes &self, so no mutable access to v is needed. The mutation happens inside the Cell, which allows it through a shared reference.
Exercise
Predict what happens when this program runs, and say whether the compiler reports a problem. use std::cell::RefCell; fn main() { let cell = RefCell::new(vec![1]); let reader = cell.borrow(); cell.borrow_mut().push(2); println!("{}", reader.len()); }
Show answer
The compiler accepts the program. At runtime, cell.borrow_mut() panics because the Ref guard reader is still alive, and RefCell allows a mutable borrow only when no other borrows exist. To fix it, drop reader before calling borrow_mut, or finish using it first.
Exercise
You need a flag shared between two functions on one thread. Each function receives &Config and one of them must set verbose to true. The field is a bool. Which type would you choose for the field, Cell<bool> or RefCell<bool>, and why?
Show answer
Use Cell<bool>. A bool is Copy, you only need to read and replace the whole value, and Cell has no runtime borrow tracking, so it cannot panic. RefCell<bool> would work but adds a counter and a possible panic for no benefit.