Sub topic 17
RefCell and interior mutability
This chapter assumes you know the borrowing rules (many &T or one &mut T), can use Box<T> and Rc<T>, and can read basic Rust syntax.
The problem: mutation behind shared access
The borrow checker enforces its rules at compile time. Sometimes the compiler cannot prove that your code is safe, even though it is. Rc<T> makes this worse. It gives you several owners, but it hands out only shared references, so you cannot mutate the value inside.
Interior mutability is a pattern that lets you mutate a value through a shared reference. RefCell<T> is the standard tool for it. It keeps the same borrowing rules but checks them at run time instead of compile time.
Using RefCell
RefCell<T> owns a value of type T. Two methods give you access:
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 cell = RefCell::new(String::from("hello"));
cell.borrow_mut().push_str(", world");
println!("{}", cell.borrow());
}The variable cell is not declared mut, yet the string changes. The mutation goes through RefCell, which tracks active borrows internally.
Run-time checking
RefCell counts how many Ref and RefMut guards are alive. If you break the rules, the program panics instead of failing to compile.
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}");
}This compiles and then panics with already borrowed: BorrowMutError. A guard lives until it goes out of scope, so a long-lived Ref or RefMut is the usual cause of a panic. Use try_borrow and try_borrow_mut if you want a Result instead of a panic.
Combining Rc and RefCell
The common pairing is Rc<RefCell<T>>. Rc provides several owners, and RefCell allows each owner to mutate the shared value.
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let shared = Rc::new(RefCell::new(vec![1]));
let other = Rc::clone(&shared);
other.borrow_mut().push(2);
println!("{:?} count={}", shared.borrow(), Rc::strong_count(&shared));
}This prints [1, 2] count=2. Both handles see the same vector.
Common errors
- Holding a guard too long. Keep the borrow in a short expression or a small block so the guard drops early.
- Borrowing in a loop or a callback. Calling a function that borrows the same cell while you still hold a guard causes a panic.
- Using it in threads.
RefCellis not thread-safe, and the compiler rejects it across threads. Later you will useMutexfor that.
Comparing the options
| Type | Borrow rules checked | Extra cost |
|---|---|---|
| `&T` / `&mut T` | Compile time | None |
| `RefCell<T>` | Run time | Borrow counter, possible panic |
Exercise
What happens when this code runs? let c = RefCell::new(1); let a = c.borrow(); let b = c.borrow_mut();
Show answer
It compiles, then panics at the borrow_mut call with a BorrowMutError. A shared Ref (a) is still alive, so RefCell refuses a mutable borrow. Dropping a first, for example by ending its scope, would make the call succeed.
Exercise
Why is Rc<RefCell<T>> used instead of Rc<T> when several owners must change the data?
Show answer
Rc<T> gives only shared references, so the data cannot be mutated. Wrapping the value in RefCell allows mutation through those shared references, with the borrowing rules checked at run time.