RefCell: checks at run time
In the previous lesson the owners of an Rc could only read the shared book. The borrowing rule goes like this: many readers at once or one person making notes, but not both.
So far the compiler has checked this rule — in advance, from the text of the program. Sometimes the text does not show that two people never write at the same time, and the compiler forbids it to be safe.
Picture a librarian at the lending desk. The librarian keeps the same rules but checks them at the moment someone comes to the desk. Readers get the book while nobody writes in it, and it goes out for notes only if nobody holds it. A rule breaker does not get through: the librarian raises the alarm.
In Rust that librarian is the RefCell type, and its alarm is a panic.
RefCell and guards
use std::cell::RefCell;
fn main() {
let c = RefCell::new(5);
let mut w = c.borrow_mut();
*w += 1;
drop(w);
let r = c.borrow();
println!("{r}"); // 6
}Let's walk through the example line by line:
use std::cell::RefCell;makes the name of the typeRefCellfrom the standard library available.RefCell::new(5)puts the number inside aRefCell.chas nomut.c.borrow_mut()asks the librarian for the right to write. The method takes&self: a shared reference, that is, a plain read-only&reference. So the compiler does not object.- The call returns a
RefMutguard that works like&mut.*w += 1changes the value through it, so the guard itself is declared aslet mut w. Unlike a&mutreference, wherelet w = &mut s;did withoutmut, a guard is an ordinary value, and you can write through it only if the variable itself is mutable. drop(w)destroys the guard, and the borrow goes back to the librarian.c.borrow()hands out aRefguard that works like&T: read only.println!("{r}")prints the value inside the guard:6.
A guard is the value that borrow or borrow_mut returned: while it is alive, the borrow is taken. Changing the contents through a shared reference, as here, is called interior mutability: from outside c is immutable, but the value inside changes.
The same rules
A RefCell keeps a count of the borrows it has handed out and checks the familiar rule against it: any number of Ref guards or one RefMut. Breaking the rule is a panic:
borrow_mut()while a guard is alive givesRefCell already borrowed;borrow()while aRefMutis alive givesRefCell already mutably borrowed.
The compiler does not catch this mistake. To it these are method calls with &self, and you can make as many of those as you like.
How does RefCell differ from &mut? Interviewers like to ask this. The compiler checks &mut at build time, and breaking the rule is a compile error. RefCell checks the same rules at run time, and breaking them is a panic.
The librarian picture is off in one respect. A real librarian asks you to wait, but a RefCell waits for nobody: a violation turns into a panic at once.
A guard lives to the block's end
The borrow of a plain reference ends at its last use. A guard is different: it holds the borrow until it is destroyed, that is, until the closing brace of the block or until drop.
use std::cell::RefCell;
fn main() {
let c = RefCell::new(1);
let r = c.borrow();
println!("{r}"); // 1
let mut w = c.borrow_mut(); // ✗
*w += 1;
println!("{w}");
}RefCell already borrowedThe program builds, prints 1 and panics. Let's see why:
ris aRefguard; it holds a read borrow.- After the
println!the variableris no longer needed, but the guard stays alive until the end ofmain. c.borrow_mut()sees a live reader and panics.
With plain references &x and &mut x the same order of lines would build: the borrow of r would end at the print. Here you have to release the guard explicitly — drop(r) before borrow_mut() — or close it inside an inner block.
Rc and RefCell together
Rc gives several owners, but read access only. RefCell gives change. Together they give a value that several owners change:
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let shelf = Rc::new(RefCell::new(vec![1]));
let anna = Rc::clone(&shelf);
anna.borrow_mut().push(2);
shelf.borrow_mut().push(3);
println!("{:?}", shelf.borrow()); // [1, 2, 3]
}Let's go step by step:
shelfandannaare two owners of one vector in aRefCell.anna.borrow_mut().push(2)takes a temporary guard. It lives until the end of the statement, the;, and releases the borrow at once.- That is why
shelf.borrow_mut()on the next line does not panic. - The changes of both owners are visible to everyone: it prints
[1, 2, 3].
Common mistake
A guard was declared without mut, and then the value was changed through it:
use std::cell::RefCell;
fn main() {
let c = RefCell::new(5);
let w = c.borrow_mut();
*w += 1; // ✗
println!("{w}");
}error[E0596]: cannot borrow `w` as mutable, as it is not declared as mutableThe program does not compile. c itself needs no mut, but the guard does: *w += 1 changes the value through w, as through a mutable variable. The fix is let mut w = c.borrow_mut();.
Key points
- A
RefCelllets you change a value through a shared reference:borrow()hands out aRefguard,borrow_mut()aRefMutguard, and theRefCellitself needs nomut. - The borrowing rules are the same but are checked at run time: a second
borrow_mut()while a guard is alive is aRefCell already borrowedpanic, not a compile error. - A guard holds the borrow until the end of the block or until
drop, not until its last use. Rc<RefCell<T>>is a value that several owners change.