Rc and RefCell: shared and interior mutability
`Rc<T>` is a reference-counted pointer: several owners share one value, and it is dropped when the last one goes. It is single-threaded only — `Arc` is the thread-safe version.
`RefCell<T>` moves the borrow check from compile time to run time. `borrow()` and `borrow_mut()` follow the same one-writer rule, but a violation panics instead of failing to compile.
`Rc<RefCell<T>>` combines them: shared ownership of something mutable. Useful, but reach for it only when plain ownership genuinely cannot express the shape of your data.
Two mutable borrows at run time
use std::cell::RefCell;
fn main() {
let cell = RefCell::new(1);
let a = cell.borrow_mut();
let b = cell.borrow_mut(); // panics
println!("{a} {b}");
}thread 'main' panicked at: already mutably borrowed: BorrowMutError
Keep each `borrow_mut()` in its own short scope. `RefCell` enforces the same rule as the compiler, just later and less forgivingly.
Run it and change it
The editor below is live: edit anything and the real compiler output updates by itself.