Sub topic 17
RefCell and Interior Mutability
This chapter assumes you know the borrowing rules (many &T or one &mut T), how Box<T> and Rc<T> work, and how to read a borrow checker error. It covers Cell, RefCell, and the pattern they enable. It builds on the previous chapter on Rc.
The problem: mutation behind shared access
The borrowing rules are checked at compile time. They say you can have many shared references or one mutable reference, never both at once. That is strict, and it is sometimes stricter than your program needs.
Rc<T> makes this concrete. It gives several owners access to one value, but it only hands out &T. You cannot write this:
use std::rc::Rc;
fn main() {
let shared = Rc::new(vec![1]);
// shared.push(2); // error: cannot borrow data in an `Rc` as mutable
println!("{:?}", shared);
}If every owner could mutate, the compiler could not prove that no two mutations overlap. So Rc refuses.
Interior mutability is a pattern where a value can be changed through a shared reference (&T). The type still follows the borrowing rules. It checks them in a different place, either inside a small, safe API or at run time, instead of through the compiler's analysis of your code.
Cell: copying values in and out
Cell<T> is the simplest interior mutability type. It never hands out a reference to its contents. You can only replace the value or copy it out, so no reference can be left dangling.
use std::cell::Cell;
struct Counter {
hits: Cell<u32>,
}
impl Counter {
fn record(&self) {
self.hits.set(self.hits.get() + 1);
}
}
fn main() {
let c = Counter { hits: Cell::new(0) };
c.record();
c.record();
println!("{}", c.hits.get());
}record takes &self, not &mut self, yet it changes hits. get requires T: Copy. For other types, use replace, take, or swap. Cell has no run-time cost for tracking, and it cannot panic.
RefCell: borrow checking at run time
RefCell<T> lets you borrow the inner value by reference. It tracks the borrows while the program runs.
| Method | Returns | Acts like |
|---|---|---|
| `borrow()` | `Ref<T>` | `&T` |
| `borrow_mut()` | `RefMut<T>` | `&mut T` |
| `try_borrow()` | `Result<Ref<T>, BorrowError>` | `&T`, no panic |
| `try_borrow_mut()` | `Result<RefMut<T>, BorrowMutError>` | `&mut T`, no panic |
Ref and RefMut are guard values. Each one adds to a counter inside the RefCell when it is created and subtracts when it is dropped. The counter enforces the same rule as the compiler: many readers or one writer.
use std::cell::RefCell;
fn main() {
let cell = RefCell::new(String::from("hello"));
{
let mut w = cell.borrow_mut();
w.push_str(", world");
} // the RefMut guard is dropped here
println!("{}", cell.borrow());
}Notice that cell is not declared mut. The mutation goes through &self.
What happens when you break the rules
If you ask for a borrow that conflicts with a live one, borrow and borrow_mut panic. The program compiles, and then fails when it runs.
use std::cell::RefCell;
fn main() {
let cell = RefCell::new(5);
let first = cell.borrow_mut();
let second = cell.borrow_mut(); // panics: already borrowed
println!("{first} {second}");
}The message is already borrowed: BorrowMutError (the exact wording varies by Rust version). The fix is to shorten the first borrow, or to use try_borrow_mut and handle the Err.
use std::cell::RefCell;
fn main() {
let cell = RefCell::new(5);
let first = cell.borrow_mut();
match cell.try_borrow_mut() {
Ok(_) => println!("got it"),
Err(e) => println!("busy: {e}"),
}
drop(first);
println!("{}", cell.try_borrow_mut().is_ok());
}Calling drop(first) ends the borrow early. This is the same idea as borrows ending at their last use, except that guards live until the end of their scope unless you drop them.
Rc<RefCell<T>>: shared and mutable
Rc provides shared ownership. RefCell provides mutation. Together they give several owners the ability to change one value.
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug)]
struct Account {
balance: i64,
}
fn main() {
let account = Rc::new(RefCell::new(Account { balance: 100 }));
let for_audit = Rc::clone(&account);
account.borrow_mut().balance -= 30;
println!("audit sees {}", for_audit.borrow().balance);
println!("{:?}, owners = {}", account, Rc::strong_count(&account));
}The temporary RefMut from account.borrow_mut() is dropped at the end of its statement. That is why the next borrow() succeeds.
A practical case: mock objects
Interior mutability is common when a trait method takes &self but an implementation needs to record something.
use std::cell::RefCell;
trait Logger {
fn log(&self, msg: &str);
}
struct MemoryLogger {
lines: RefCell<Vec<String>>,
}
impl Logger for MemoryLogger {
fn log(&self, msg: &str) {
self.lines.borrow_mut().push(msg.to_string());
}
}
fn run(logger: &dyn Logger) {
logger.log("started");
logger.log("finished");
}
fn main() {
let logger = MemoryLogger { lines: RefCell::new(Vec::new()) };
run(&logger);
println!("{:?}", logger.lines.borrow());
}The trait promises &self, so callers do not need exclusive access. RefCell lets the implementation still keep state.
Edge cases and gotchas
- Panics instead of compile errors. A conflicting borrow is caught only when that code path runs. A test suite that never reaches the path will miss it.
- Guards live longer than you expect. In
match cell.borrow().get(0) { ... }, the temporary guard can live for the wholematch. Callingborrow_mutinside the arms then panics. Copy the value out first. - Not thread-safe.
RefCellandCellare notSync, so you cannot share them between threads. The next chapter coversMutex, which plays the same role across threads and blocks instead of panicking. - Reference cycles leak. If
Rc<RefCell<Node>>values point at each other, the counts never reach zero and the memory is never freed. UseWeak<T>for back-pointers. - Small run-time cost. Each borrow updates a counter and checks it. This rarely matters, but it is not free.
Choosing a type
| Situation | Use |
|---|---|
| Small `Copy` value changed through `&self` | `Cell<T>` |
| Non-`Copy` value changed through `&self`, single thread | `RefCell<T>` |
| Several owners that all need to mutate, single thread | `Rc<RefCell<T>>` |
| Several threads that need to mutate | `Arc<Mutex<T>>` |
Prefer ordinary &mut T when the compiler accepts it. Reach for interior mutability when the design genuinely needs shared access with mutation, since it replaces a compile-time guarantee with a run-time check.
Exercise
This program compiles but panics when run. Explain why, and change one line so that it runs and prints 3. use std::cell::RefCell; fn main() { let cell = RefCell::new(vec![1, 2]); let first = cell.borrow(); cell.borrow_mut().push(3); println!("{} {}", first.len(), cell.borrow().len()); }
Show answer
The Ref guard first is still alive when borrow_mut is called, so the cell has an active shared borrow and the mutable borrow panics. Capture the length before mutating, for example let n = cell.borrow().len(); in place of holding first, then call cell.borrow_mut().push(3); and print n and cell.borrow().len(). A second fix is drop(first); before the borrow_mut line, after copying out first.len(). In both cases the guard is gone before the mutable borrow, so the program prints the lengths without panicking. The final length is 3.
Exercise
Why can Cell<i32> not be used when the inner type is String and you want to read the text through get? Name the method you would use to take the string out instead.
Show answer
Cell::get copies the value out, so it requires T: Copy, and String is not Copy. Use take, which swaps in the default value (an empty string) and returns the old one, or replace to swap in a specific value. If you need to read the text without removing it, use RefCell<String> and call borrow.