Sub topic 13
Interior mutability with RefCell
This chapter assumes you know shared references (&T), mutable references (&mut T), and the rule that a value has either many readers or one writer at a time. It also assumes you can use Rc for shared ownership at a basic level. Here you will see how RefCell<T> moves that rule from compile time to run time, and when that is worth doing.
The problem: a rule that is too strict
The borrow checker enforces "many readers or one writer" at compile time. It is conservative. If it cannot prove that your code follows the rule, it rejects the code, even when the code would be safe.
Some designs need mutation through a shared reference:
- Several owners hold the same value, and any of them may update it.
- A method takes
&selfbecause of a trait signature, but needs to update a cache or a counter. - A data structure is built from nodes that point at each other.
Interior mutability is a pattern that lets you change a value through a shared reference. The type's own code enforces the aliasing rule, either with run-time checks or by restricting what you can do. The unsafe code that makes this possible lives inside the standard library. You use a safe API.
RefCell basics
RefCell<T> owns a T and tracks borrows while the program runs. You ask it for a borrow with two methods:
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 c = RefCell::new(vec![1]);
c.borrow_mut().push(2);
println!("{:?}", c.borrow());
}Notice that c is not declared mut. You can change the vector because borrow_mut takes &self, not &mut self.
Ref and RefMut are guard values. A guard increments a counter inside the RefCell when it is created and decrements it when it is dropped. The cell uses that counter to decide whether a new borrow is allowed.
The rules are the same as for ordinary references. Many Ref guards can exist together, or exactly one RefMut, never both. The difference is when a violation is reported.
| Row | `&T` / `&mut T` | `RefCell<T>` |
|---|---|---|
| Rule checked | At compile time | At run time |
| Violation result | Compile error | Panic |
| Cost | None | A counter update per borrow |
| Accepts safe code the checker cannot prove | No | Yes |
What a violation looks like
This program compiles, then panics when it runs:
use std::cell::RefCell;
fn main() {
let c = RefCell::new(vec![1]);
let first = c.borrow();
c.borrow_mut().push(2);
println!("{}", first[0]);
}first is a live Ref, so the cell is in the shared state. The call to borrow_mut then asks for exclusive access, and the cell panics with a message that says it is already borrowed. Compare this with the compile-time version of the same mistake, error E0502 from earlier chapters. The code is the same, but the error moves from your terminal at build time to a crash at run time, possibly in production.
Checking without panicking
If a failed borrow is a normal situation in your program, use the fallible versions. try_borrow and try_borrow_mut return a Result instead of panicking.
use std::cell::RefCell;
fn main() {
let c = RefCell::new(5);
let r = c.borrow();
match c.try_borrow_mut() {
Ok(mut m) => *m += 1,
Err(_) => println!("busy, value is {}", *r),
}
}This prints busy, value is 5. Most code should be structured so the borrows never conflict, rather than handling the error. These methods are mainly useful for re-entrant code, such as callbacks that might run while a borrow is held.
Guards live until they are dropped
Most RefCell panics come from a guard living longer than you expected. A guard created in the middle of an expression is a temporary. It is dropped at the end of the enclosing statement, not after the method call returns.
This line panics:
use std::cell::RefCell;
fn main() {
let c = RefCell::new(vec![1usize]);
c.borrow_mut().push(c.borrow().len());
}The receiver c.borrow_mut() is evaluated first and produces a RefMut. That guard stays alive while the argument c.borrow().len() is evaluated, so the second borrow finds the cell already mutably borrowed. The fix is to finish the read in its own statement:
use std::cell::RefCell;
fn main() {
let c = RefCell::new(vec![1usize]);
let len = c.borrow().len();
c.borrow_mut().push(len);
println!("{:?}", c.borrow());
}In let len = c.borrow().len(); the Ref is dropped at the semicolon. Only the usize survives, and it does not borrow from the cell.
Two habits prevent most of these panics:
- Copy or clone the data you need out of the guard, then let the guard go.
- Keep guards in small scopes. Use a block
{ ... }ordrop(guard)to end a borrow early.
The common pairing: Rc<RefCell<T>>
Rc<T> gives several owners access to one value, but only through shared references. On its own it cannot hand out &mut T while other owners exist. Wrapping the value in a RefCell supplies the missing mutation.
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let log = Rc::new(RefCell::new(Vec::<String>::new()));
let a = Rc::clone(&log);
let b = Rc::clone(&log);
a.borrow_mut().push("from a".to_string());
b.borrow_mut().push("from b".to_string());
println!("{:?}", log.borrow());
println!("owners: {}", Rc::strong_count(&log));
}This prints both strings and owners: 3. Each borrow_mut() is a temporary that ends at its semicolon, so the borrows never overlap.
Two limits apply:
RcandRefCellare for a single thread. Neither isSync, so the compiler refuses to share them across threads. In multithreaded code the equivalents areArc<Mutex<T>>orArc<RwLock<T>>.- If two
Rcvalues point at each other, their reference counts never reach zero and the memory leaks. UseWeak<T>for back-pointers such as a child's link to its parent.
Cell for simple values
Cell<T> is a lighter form of interior mutability. It never hands out references to its contents. You can only get a copy or set a new value, so no aliasing rule can be broken and no run-time check is needed.
use std::cell::Cell;
struct Counter {
hits: Cell<u32>,
}
impl Counter {
fn hit(&self) {
self.hits.set(self.hits.get() + 1);
}
}
fn main() {
let c = Counter { hits: Cell::new(0) };
c.hit();
c.hit();
println!("{}", c.hits.get());
}The method hit takes &self, yet it updates state. This prints 2. get requires T: Copy. For other types, Cell offers replace and take.
Choosing a tool
| Situation | Use |
|---|---|
| One owner, mutation through `&mut` is possible | Plain `&mut T`. This is the default. |
| A small `Copy` value updated through `&self` | `Cell<T>` |
| A larger value updated through `&self`, single thread | `RefCell<T>` |
| Several owners, single thread | `Rc<RefCell<T>>` |
| Several owners, several threads | `Arc<Mutex<T>>` |
Reach for RefCell after you have tried restructuring. Many borrow errors disappear if you split a struct into separate fields, shorten a borrow, or pass values as arguments instead of storing them. RefCell trades a compile-time guarantee for a run-time risk, so it should be a deliberate choice.
Common mistakes
- Holding a guard across a call that borrows again. A function that borrows the cell while its caller still holds a guard will panic. Document which functions borrow, or pass the borrowed data in as a parameter.
- Returning a reference from a borrow.
c.borrow().first()returns a reference tied to a temporary guard, and the compiler rejects returning it. Return a clone or aRef(for example withRef::map) instead. - Using
RefCellto avoid learning the borrow checker. If every field is wrapped inRc<RefCell<_>>, you have given up compile-time checking across the whole design and gained panics. - Expecting thread safety.
RefCellisSendwhenTis, but it is notSync, so you cannot share&RefCell<T>orRc<RefCell<T>>between threads.
Exercise
This program compiles. Does it run to completion or panic? If it panics, change one line so it prints [1, 2].
use std::cell::RefCell;
fn main() {
let c = RefCell::new(vec![1]);
let total = c.borrow();
c.borrow_mut().push(2);
println!("{:?} {}", c.borrow(), total.len());
}
Show answer
It panics. total is a live Ref, so the cell is in the shared-borrow state when borrow_mut() asks for exclusive access. Fix it by copying the length out so the guard is dropped at the semicolon: let total = c.borrow().len(); and print total instead of total.len(). The final line then borrows only once more, after the mutable borrow has ended, and prints [1, 2] 1.