Sub topic 12
Rc<RefCell<T>>: shared, mutable data
This chapter assumes you know ownership and borrowing, and that you have met Rc<T> (shared ownership with a reference count) and RefCell<T> (borrow rules checked at runtime). Here you combine them.
Why combine them
Rc<T> gives several owners to one value, but it only hands out shared references (&T). You cannot mutate the value through it. RefCell<T> allows mutation through a shared reference, but it has a single owner.
Wrap a RefCell<T> in an Rc, and you get several owners of a value that any of them can mutate. The type is written Rc<RefCell<T>>. It is for single-threaded code only.
A worked example
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let shared = Rc::new(RefCell::new(vec![1, 2, 3]));
let other = Rc::clone(&shared);
other.borrow_mut().push(4);
println!("{:?}", shared.borrow());
}The program prints [1, 2, 3, 4]. Both handles point to the same RefCell<Vec<i32>>. A push through other is visible through shared.
Three things happen in this code:
Rc::new(RefCell::new(...))allocates the vector inside aRefCell, inside anRc.Rc::clone(&shared)raises the strong count to 2. It does not copy the vector.borrow_mut()returns aRefMutguard. It is a temporary here, so it is dropped at the end of the statement. That releases the mutable borrow beforeshared.borrow()runs.
Where the checks happen
Two separate mechanisms are at work:
| Concern | Handled by | When it is checked |
|---|---|---|
| Who owns the value and when it is freed | `Rc` | Runtime, through the reference count |
| Who may read or write the value now | `RefCell` | Runtime, through the borrow state |
Because RefCell checks borrows at runtime, a mistake compiles but panics. This code panics:
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let shared = Rc::new(RefCell::new(String::from("hi")));
let other = Rc::clone(&shared);
let first = shared.borrow_mut();
let second = other.borrow_mut(); // panics: already mutably borrowed
println!("{first} {second}");
}The panic message is already borrowed: BorrowMutError. Cloning the Rc does not give you a second independent borrow. Both handles share one borrow state.
Common errors
- Holding a guard too long. A
ReforRefMutkept in a variable blocks other borrows until it goes out of scope. Keep guards in short statements, or end them early withdrop. - Borrowing again inside a call. If a function holds
borrow_mut()and calls code that borrows the same cell, it panics. Usetry_borrow_mut()when you want anErrinstead of a panic. - Cloning the wrong thing.
shared.clone()clones theRchandle. To copy the data, writeshared.borrow().clone(). - Using it across threads. Neither
RcnorRefCellis thread-safe, so the compiler rejects sending them to another thread. UseArc<Mutex<T>>instead.
Exercise
In the worked example, what happens if you replace other.borrow_mut().push(4); with let guard = other.borrow_mut(); guard.push(4); and then call shared.borrow() in the println! while guard is still in scope? How do you fix it?
Show answer
The program panics with already mutably borrowed: BorrowError, because guard still holds the mutable borrow. Also, guard must be declared mut to call push. Fix it by calling drop(guard) before shared.borrow(), or by keeping the borrow in a smaller scope or a single statement.