`RefCell`
RefCell<T> moves the borrow rules to runtime. borrow and borrow_mut return guards; a conflicting borrow panics instead of failing to compile.
Detailed Explanation
The borrow checker is static. Sometimes the aliasing is safe but the compiler cannot see it: a tree where a method needs &self to look up a child and then mutate that child through a map of RefCells. RefCell<T> stores a T and a runtime borrow flag. borrow() increments a shared count and returns Ref<T>. borrow_mut() requires the count to be zero and returns RefMut<T>. Dropping the guard restores the count.
A second borrow_mut while a borrow is live panics: already borrowed: BorrowMutError. That panic is the borrow checker arriving late. In a library path that can be triggered by a user, prefer try_borrow / try_borrow_mut and return a Result.
RefCell is Send if T is, and never Sync. You cannot share a RefCell across threads. The pair for threads is Mutex. The pair for single-thread sharing is Rc<RefCell<T>>. RefCell alone does not share ownership; it only allows mutation through a shared &RefCell<T>.
This is interior mutability: the RefCell is not declared mut, and you still mutate the inside. Cell<T> is the sibling for Copy types that you get and set by value without a guard. Prefer Cell for flags and counters on one thread; prefer RefCell for larger T.
When you reach for RefCell: single-thread graphs and caches the static checker cannot model. When you reach for mut: the usual case. When you reach for Mutex: more than one thread.
Nested borrows through the same RefCell are the usual panic: a method that borrow_muts self.inner and then calls another method that also borrows it. Flatten the methods so one guard covers the work, or split the RefCell into two cells for the two fields. The panic backtrace points at the second borrow; the design bug is the overlapping methods.
Code Examples
use std::cell::RefCell;
fn main() {
let n = RefCell::new(1);
*n.borrow_mut() += 1;
println!("{}", *n.borrow()); // prints: 2
}Common Gotchas
A conflicting borrow panics
`borrow_mut` while a `Ref` is live is a crash. Scope the first guard, or use `try_borrow`.
`RefCell` is not `Sync`
`Arc<RefCell<T>>` will not go to another thread. That is `Mutex`.
The outer binding need not be `mut`
Interior mutability is the point. `let n = RefCell::new(...)` is enough.
Holding a `Ref` across a call that mutates the same cell is a panic waiting
Drop the guard first, or restructure.