Sub topic 11
RefCell<T>: borrow rules checked at runtime
This chapter assumes you know Rust's borrowing rules (any number of &T, or exactly one &mut T), basic generics, and how Rc<T> shares ownership. It builds on the previous chapter's idea of interior mutability.
The problem RefCell solves
The compiler checks borrow rules conservatively. Some programs are valid, but the compiler cannot prove it. RefCell<T> is for those cases. It owns a value of type T and lets you mutate that value through a shared reference. It enforces the same rules as the compiler, but it checks them while the program runs.
With & and &mut, a violation is a compile error. With RefCell<T>, a violation is a panic. The rules did not change. Only the time of the check did.
Borrowing at runtime
RefCell<T> has two main methods:
borrow()returns aRef<T>, which acts like&T.borrow_mut()returns aRefMut<T>, which acts like&mut T.
The cell counts how many Ref and RefMut guards are alive. Many Ref guards can exist together, or one RefMut can exist alone. If you ask for a borrow that breaks this rule, borrow and borrow_mut panic. The methods try_borrow and try_borrow_mut return a Result instead.
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());
}The program prints value = 6. While first is alive, a second try_borrow_mut returns Err. Calling borrow_mut there would panic. After drop(first), the borrow is released and the next one succeeds.
Guards and lifetimes
Ref and RefMut are smart pointers. They implement Deref (and DerefMut), and they implement Drop. Dropping a guard decrements the cell's borrow count. So a borrow lasts until the guard goes out of scope, not until you last use it.
This is why *cell.borrow_mut() += 1; is safe. The guard is a temporary, and it is dropped at the end of that statement.
Common errors
- Holding a guard too long. A
letbinding keeps the guard alive until the end of the block. Wrap it in a smaller block, or calldrop, before borrowing again. - Borrowing again inside a call. If you hold
borrow_mut()and call a function that borrows the same cell, it panics. - Assuming the compiler will catch it. It will not. A conflict that only happens on some code paths may pass all your tests and still panic in production.
When to use it
Reach for RefCell<T> when you have a single owner or a shared structure, you need to mutate through &self, and the borrow pattern is correct but hard to prove statically. Prefer plain &mut when it works. It costs nothing at runtime, and the compiler catches mistakes for you.
Exercise
What happens at runtime if you call cell.borrow() while a RefMut from cell.borrow_mut() is still alive? How could you check for this without panicking?
Show answer
borrow() panics, because a mutable borrow is active and shared borrows are not allowed at the same time. To avoid the panic, call try_borrow(), which returns Err in this case.