RefCell<T> (Rust)
RefCell<T> provides interior mutability: it lets you mutate data through a shared reference by moving Rust's borrow checking from compile time to runtime. Borrow rules are still enforced — violations panic.
Rust
Normally Rust forbids mutating through an immutable reference. RefCell<T> works around this safely: you call .borrow() for a shared read or .borrow_mut() for an exclusive write, and it checks the borrow rules dynamically. Break them (e.g. two mutable borrows at once) and it panics rather than allowing a data race.
RefCell is single-threaded. Its typical use is inside Rc as Rc<RefCell<T>>, giving multiple owners the ability to mutate shared data — common in tree and graph structures. For multithreaded interior mutability use Mutex.
The trade-off versus normal borrowing is that mistakes surface at runtime (a panic) instead of compile time. Use RefCell only when the ownership graph genuinely requires interior mutability.
Syntax
use std::cell::RefCell;
let c = RefCell::new(5);
*c.borrow_mut() += 1;Examples
Rust
use std::cell::RefCell;
fn main() {
let cell = RefCell::new(vec![1, 2]);
cell.borrow_mut().push(3);
println!("{:?}", cell.borrow());
}Output:
[1, 2, 3]