Sub topic 11
RefCell<T>: borrow rules checked at runtime
This chapter assumes you know Rust's ownership and borrowing rules, can read basic generic and trait code, and have seen Box<T> and Rc<T>. You should recall that the compiler allows either one &mut T or any number of &T at a time, never both.
The problem RefCell solves
The compiler checks borrow rules statically. It is conservative: if it cannot prove a program is safe, it rejects the program, even when the program would be fine at runtime. Some designs are correct but cannot be expressed to the compiler. A mock object that records the calls made to it is a common example. The trait method takes &self, yet the mock must change its own state.
RefCell<T> handles this case. It owns a value of type T and lets you borrow that value mutably or immutably through a shared reference. The borrow rules still apply. The difference is when they are checked:
| Type | Borrow rules checked | Violation result |
|---|---|---|
| `&T` / `&mut T` | Compile time | Compile error |
| `Box<T>` | Compile time | Compile error |
| `RefCell<T>` | Run time | Panic (or `Err` with the `try_` methods) |
RefCell<T> is single-threaded. It does not implement Sync, so the compiler stops you from sharing it across threads.
The core API
You mostly use four methods:
borrow()returns aRef<T>, a smart pointer that acts like&T. It panics if a mutable borrow is active.borrow_mut()returns aRefMut<T>, which acts like&mut T. It panics if any other borrow is active.try_borrow()andtry_borrow_mut()return aResultinstead of panicking.
Ref and RefMut implement Deref (and RefMut implements DerefMut), so you use them like ordinary references. They also implement Drop. The RefCell keeps a counter of active borrows, and dropping a Ref or RefMut decrements it. This is the same Drop mechanism from earlier chapters, applied to bookkeeping.
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());
}This program prints value = 6. Step by step:
borrow_mut()returns aRefMutnamedfirst. The cell now records one active mutable borrow.try_borrow_mut()whilefirstis alive returnsErr, so the assertion passes. A plainborrow_mut()here would panic.drop(first)releases the borrow. The nexttry_borrow_mut()succeeds, and its temporaryRefMutis dropped at the end of that statement.*cell.borrow_mut() += 1takes a temporary mutable borrow, writes through it, and releases it at the end of the statement.cell.borrow()takes a shared borrow for theprintln!.
Notice that cell is not declared mut. Mutation happens through a shared reference to the cell. That is what "interior mutability" means.
How the runtime tracking works
Internally, a RefCell stores your value plus a borrow flag. The flag represents one of three states: unborrowed, borrowed by one or more shared Refs (with a count), or borrowed by one RefMut.
placeholderThe state machine below shows the transitions.
The check costs a small amount of work on every borrow: a read and a write of the flag. It also adds one word of storage to the cell. These costs are small, but they are not zero, and they are paid even when your code never violates the rules.
When a violation happens
The compiler cannot see a violation, so the program compiles and then panics. This version compiles without errors:
use std::cell::RefCell;
fn main() {
let cell = RefCell::new(vec![1, 2, 3]);
let reader = cell.borrow();
println!("first element = {}", reader[0]);
// `reader` is still alive here, so this panics at runtime.
cell.borrow_mut().push(4);
}The panic message is already borrowed: BorrowMutError (the exact wording varies by Rust version). The cause is the lifetime of reader. It lives until the end of main, not until its last use in the way a plain reference does under non-lexical lifetimes. Ref has a Drop implementation, so it stays alive until its scope ends. Dropping it early with drop(reader) or wrapping it in an inner block fixes the program.
Choosing between panicking and fallible borrows
Use borrow() and borrow_mut() when a conflict would mean a bug in your program. A panic with a stack trace is a good way to find such a bug. Use try_borrow() and try_borrow_mut() when a conflict is an expected condition you can handle, for example when reentrant callbacks might touch the same cell and you want to skip or retry.
use std::cell::RefCell;
fn try_append(log: &RefCell<Vec<String>>, line: &str) -> bool {
match log.try_borrow_mut() {
Ok(mut entries) => {
entries.push(line.to_string());
true
}
Err(_) => false,
}
}
fn main() {
let log = RefCell::new(Vec::new());
println!("first append: {}", try_append(&log, "start"));
let reader = log.borrow();
println!("append while reading: {}", try_append(&log, "blocked"));
println!("entries seen by reader: {}", reader.len());
drop(reader);
println!("append after drop: {}", try_append(&log, "done"));
}The output is:
first append: true
append while reading: false
entries seen by reader: 1
append after drop: trueA realistic use: a mock that records calls
The classic use is a test double. A trait method takes &self, so the implementation needs interior mutability to record what happened.
use std::cell::RefCell;
trait Messenger {
fn send(&self, msg: &str);
}
struct MockMessenger {
sent: RefCell<Vec<String>>,
}
impl Messenger for MockMessenger {
fn send(&self, msg: &str) {
self.sent.borrow_mut().push(msg.to_string());
}
}
fn notify(messenger: &dyn Messenger, usage: u32) {
if usage > 90 {
messenger.send("Warning: over 90% of quota used");
}
}
fn main() {
let mock = MockMessenger { sent: RefCell::new(vec![]) };
notify(&mock, 95);
notify(&mock, 10);
println!("messages sent: {}", mock.sent.borrow().len());
}This prints messages sent: 1. The trait signature stays &self, which matches how real implementations will be written, and the mock still records state.
Edge cases and gotchas
- Temporaries in one expression.
cell.borrow_mut().push(cell.borrow().len())panics. Theborrow_mut()guard is created first and is still alive whenborrow()runs. Compute the length into a local first. - Re-entrancy. If a method holds a
RefMutand calls code that borrows the same cell, you get a panic. Releasing the guard before the call avoids it. - Guards across long operations. Holding a
Refwhile calling unknown code is risky for the same reason. - Panics in the middle of a mutation. If a panic unwinds while a
RefMutis held, the guard is dropped and the borrow is released. The value may be left half-updated, so design mutations to keep invariants valid. - No compile-time safety net. A violation is a logic bug that tests must find. Prefer ordinary references when the compiler accepts them.
RefCellis the right tool only when static checking cannot express your design. - Not for threads. Use
MutexorRwLockwhen several threads need this behavior. They block or wait instead of panicking.
Summary of the model
RefCell<T> gives you the same rules as references, enforced with a counter at run time. It trades a compile-time guarantee for flexibility, and the price is a possible panic and a small cost per borrow. The next chapters combine it with Rc<T> to share mutable data.
Exercise
The following program compiles. Does it run to completion? If not, explain why and show a fix that keeps the same output. use std::cell::RefCell; fn main() { let data = RefCell::new(vec![1, 2, 3]); let first = data.borrow(); data.borrow_mut().push(first[0] + 10); println!("{:?}", data.borrow()); }
Show answer
It panics at the borrowmut call. The Ref named first is still alive, so the cell is shared-borrowed and a mutable borrow is a violation. Copy the value out and release the guard first: let first = data.borrow()[0]; (the temporary Ref is dropped at the end of that statement), then data.borrowmut().push(first + 10);. The output is [1, 2, 3, 11].
Exercise
When would you choose tryborrowmut over borrow_mut, and what does it return when the cell is already borrowed?
Show answer
Use tryborrowmut when a conflicting borrow is an expected situation your code can handle, such as reentrant callbacks, so you can skip or retry instead of crashing. It returns Err(BorrowMutError) when any other borrow is active, and Ok(RefMut) otherwise. Use borrow_mut when a conflict would be a bug, so the panic exposes it.