Sub topic 13
Interior Mutability with RefCell
This chapter assumes you know ownership and moves, shared (&T) and mutable (&mut T) references, and the rule that a value has either many shared borrows or one mutable borrow at a time. You should be able to build and run a program with cargo.
Why the compile-time rules sometimes get in the way
The borrow checker enforces "many readers or one writer" while your program compiles. This is safe, but it is conservative. Some correct designs cannot be shown to follow the rules at compile time. For example, several parts of a program may need to read a value through shared references, while one of them occasionally updates a private detail such as a cache or a counter.
Interior mutability is the pattern for these cases. A type with interior mutability lets you change its contents through a shared reference. The rules do not go away. The check moves from compile time to run time.
RefCell basics
RefCell<T> is a type in std::cell that owns a value of type T and tracks borrows of it while the program runs. You do not take & or &mut of the inner value directly. You call two methods instead:
borrow()returns a guard that acts like a shared reference.borrow_mut()returns a guard that acts like a mutable reference.
A guard is a small value that releases the borrow when it is dropped.
use std::cell::RefCell;
fn main() {
let c = RefCell::new(vec![1]);
c.borrow_mut().push(2);
println!("{:?}", c.borrow());
}The variable c is not declared mut. The vector still changes, because borrow_mut works through a shared reference to the RefCell. Each guard in this example lives only until the end of its statement, so the borrows never overlap.
The rules still apply at run time
RefCell keeps a count of active guards. It applies the same rule as the compiler: any number of borrow() guards, or exactly one borrow_mut() guard, never both. If you break the rule, the program does not fail to compile. It panics.
use std::cell::RefCell;
fn main() {
let c = RefCell::new(5);
let first = c.borrow_mut();
let second = c.borrow_mut(); // panics: already mutably borrowed
println!("{first} {second}");
}This compiles, then panics with a message like already borrowed: BorrowMutError when it reaches the second call. If you want to handle the conflict instead of panicking, use try_borrow and try_borrow_mut, which return a Result.
Common errors
- Holding a guard too long. A guard stored in a variable lives until the end of its scope. Keep guards in short statements, or end the scope with braces or
drop(guard)before borrowing again. - Expecting compile-time help. The compiler will not warn you about overlapping
RefCellborrows. Only running the code reveals them, so tests need to exercise those paths. - Using it as a shortcut. If a plain
&mut Tworks, use it. A compile error is better than a run-time panic. - Sharing across threads.
RefCellis not thread-safe. Across threads, useMutexorRwLock.
When to use it
Reach for RefCell when ownership or borrowing is correct in principle but the compiler cannot see it. Typical cases are caching results behind a method that takes &self, test doubles that record calls, and, together with Rc, data that several owners must modify. Prefer the earlier tools first: borrow, move, or clone as the previous chapter describes.
Exercise
The code below compiles. Why does it panic when run, and how would you fix it? use std::cell::RefCell; fn main() { let c = RefCell::new(vec![1]); let r = c.borrow(); c.borrow_mut().push(2); println!("{:?}", r); }
Show answer
The shared guard r is still alive when borrow_mut() is called, because r is used later in println!. RefCell sees a shared and a mutable borrow at once and panics. Fix it by finishing with r first, for example by moving the borrow_mut().push(2) line before let r = c.borrow();, or by putting r in an inner block that ends before the mutation.