Skip to content
Theory · Smart pointers · lesson 5 of 6

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

Rust
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:

  1. use std::cell::RefCell; makes the name of the type RefCell from the standard library available.
  2. RefCell::new(5) puts the number inside a RefCell. c has no mut.
  3. 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.
  4. The call returns a RefMut guard that works like &mut. *w += 1 changes the value through it, so the guard itself is declared as let mut w. Unlike a &mut reference, where let w = &mut s; did without mut, a guard is an ordinary value, and you can write through it only if the variable itself is mutable.
  5. drop(w) destroys the guard, and the borrow goes back to the librarian.
  6. c.borrow() hands out a Ref guard that works like &T: read only.
  7. 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 gives RefCell already borrowed;
  • borrow() while a RefMut is alive gives RefCell 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.

Rust
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}");
}
TEXT
RefCell already borrowed

The program builds, prints 1 and panics. Let's see why:

  1. r is a Ref guard; it holds a read borrow.
  2. After the println! the variable r is no longer needed, but the guard stays alive until the end of main.
  3. 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:

Rust
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:

  1. shelf and anna are two owners of one vector in a RefCell.
  2. anna.borrow_mut().push(2) takes a temporary guard. It lives until the end of the statement, the ;, and releases the borrow at once.
  3. That is why shelf.borrow_mut() on the next line does not panic.
  4. 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:

Rust
use std::cell::RefCell;

fn main() {
    let c = RefCell::new(5);
    let w = c.borrow_mut();
    *w += 1; // ✗
    println!("{w}");
}
TEXT
error[E0596]: cannot borrow `w` as mutable, as it is not declared as mutable

The 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 RefCell lets you change a value through a shared reference: borrow() hands out a Ref guard, borrow_mut() a RefMut guard, and the RefCell itself needs no mut.
  • The borrowing rules are the same but are checked at run time: a second borrow_mut() while a guard is alive is a RefCell already borrowed panic, 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.