Sub topic 12
Rc<RefCell<T>>: shared, mutable data
This chapter assumes you know ownership, moves, and borrowing rules. It also assumes you have met Rc<T> (several owners of one value) and RefCell<T> (borrow rules checked at runtime). Here you combine the two to get shared, mutable data in single-threaded code.
Why neither type is enough alone
Rc<T> gives several owners, but it only hands out shared references (&T). You cannot mutate through it. RefCell<T> allows mutation through a shared reference, but it has exactly one owner. Wrapping a RefCell<T> in an Rc gives you both: many owners, and mutation through any of them.
| Type | Owners | Mutation | Borrow checking |
|---|---|---|---|
| `Rc<T>` | Many | Not allowed | Compile time |
| `RefCell<T>` | One | Allowed through `&` | Runtime |
| `Rc<RefCell<T>>` | Many | Allowed through `&` | Runtime |
The basic pattern
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 shared and other point to the same RefCell<Vec<i32>>. The push through other is visible through shared.
Three things are happening in this code:
Rc::clone(&shared)copies the pointer and increments the strong count. It does not copy the vector.other.borrow_mut()reaches theRefCellthroughRc'sDerefimplementation. It returns aRefMut<Vec<i32>>.- The
RefMutis a temporary. It is dropped at the end of the statement, which releases the mutable borrow. The latershared.borrow()therefore succeeds.
How the layers fit together
The Rc tracks ownership. The RefCell tracks active borrows. The two counters are independent. The strong count says how many owners exist. The borrow flag says how many Ref guards or one RefMut guard are alive right now.
Runtime borrow rules still apply
RefCell enforces the usual rule at runtime: any number of shared borrows, or exactly one mutable borrow, never both. Rc does not relax that rule. Two owners can each try to borrow mutably, and the second attempt will fail.
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let a = Rc::new(RefCell::new(5));
let b = Rc::clone(&a);
let first = a.borrow_mut();
assert!(b.try_borrow_mut().is_err());
assert!(b.try_borrow().is_err());
drop(first);
*b.borrow_mut() += 1;
println!("value = {}", a.borrow());
}The program prints value = 6. While first is alive, both try_borrow_mut and try_borrow on the other handle return Err. Calling borrow_mut there instead would panic with an "already borrowed" message.
A realistic example: a shared counter log
A common use is a value that several components update. Each component keeps its own Rc handle.
use std::cell::RefCell;
use std::rc::Rc;
struct Logger {
lines: Rc<RefCell<Vec<String>>>,
name: &'static str,
}
impl Logger {
fn log(&self, message: &str) {
self.lines
.borrow_mut()
.push(format!("[{}] {}", self.name, message));
}
}
fn main() {
let lines = Rc::new(RefCell::new(Vec::new()));
let net = Logger { lines: Rc::clone(&lines), name: "net" };
let disk = Logger { lines: Rc::clone(&lines), name: "disk" };
net.log("connected");
disk.log("flushed");
net.log("closed");
for line in lines.borrow().iter() {
println!("{line}");
}
println!("owners = {}", Rc::strong_count(&lines));
}The output is:
[net] connected
[disk] flushed
[net] closed
owners = 3log takes &self, not &mut self. That is the point of interior mutability: callers hold only shared references, yet the log grows. The count of 3 includes lines itself plus the two loggers.
Edge cases and common errors
Holding a guard across a call that borrows again
The most frequent panic comes from a guard that stays alive longer than you expect.
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let data = Rc::new(RefCell::new(vec![1, 2, 3]));
for item in data.borrow().iter() {
if *item == 2 {
// The iterator's Ref guard is still alive here.
assert!(data.try_borrow_mut().is_err());
}
}
// Safe version: finish reading, then mutate.
let has_two = data.borrow().contains(&2);
if has_two {
data.borrow_mut().push(99);
}
println!("{:?}", data.borrow());
}This prints [1, 2, 3, 99]. The Ref created by data.borrow() in the for header lives for the whole loop. Writing data.borrow_mut().push(...) inside the loop would panic. The fix is to end the read before the write, as the second half shows. A let binding that copies out what you need, or a short block, does this.
Cloning the handle versus cloning the data
Rc::clone(&x) shares the RefCell. x.borrow().clone() copies the inner value into an independent one. Mixing these up gives either surprising sharing or surprising isolation. Prefer Rc::clone(&x) over x.clone() so the intent is visible.
Not thread safe
Rc and RefCell are not Sync, and Rc is not Send. The compiler rejects sending an Rc<RefCell<T>> to another thread. The multithreaded counterpart is Arc<Mutex<T>>, covered in a later chapter.
Cycles
Two Rc handles that point at each other through RefCell fields never reach a strong count of zero, so their memory is never freed. This is the subject of the next chapters, where Weak<T> breaks the cycle.
When to use it, and when not to
Use Rc<RefCell<T>> when several parts of a single-threaded program must own and modify the same value, and ownership cannot be arranged as a tree. Graphs, observer lists, and shared caches are typical cases.
Consider alternatives first:
- If one owner is enough, use plain ownership and
&mut. It is checked at compile time and has no overhead. - If the shared data is a small
Copyvalue,Rc<Cell<T>>avoids borrow flags and runtime panics. - If you only need to share read-only data,
Rc<T>alone is enough.
Exercise
In the following code, which line panics at runtime, and why? let a = Rc::new(RefCell::new(String::from("hi"))); let b = Rc::clone(&a); let r = a.borrow(); b.borrow_mut().push('!'); println!("{}", r);
Show answer
The call b.borrow_mut() panics. The guard r from a.borrow() is still alive because it is used later in println!, and a and b share the same RefCell. A mutable borrow is not allowed while a shared borrow exists. The compiler cannot detect this, so it fails at runtime. Fix it by printing before the mutation or by dropping r first.
Exercise
What does Rc::strong_count report after let a = Rc::new(RefCell::new(0)); let b = Rc::clone(&a); { let _c = Rc::clone(&b); } , and does a call to a.borrow_mut() change that count?
Show answer
It reports 2, because _c was dropped at the end of its block, leaving a and b. Calling borrow_mut() does not change the count. The strong count tracks owners, while the RefCell borrow flag tracks active borrows, and the two are independent.