🦀 Rust Intermediate

What is interior mutability in Rust?

Answer

Interior mutability is a design pattern that allows you to mutate data even when you only have an immutable reference to it — bypassing Rust's normal borrowing rules by moving the borrow check to runtime. Cell<T> works for Copy types — get/set values without references. RefCell<T> works for any type — call .borrow() for an immutable borrow or .borrow_mut() for a mutable borrow; if the rules would be violated, it panics at runtime instead of failing at compile time. Mutex<T> and RwLock<T> do the same but with OS-level locking for thread safety. Interior mutability is necessary for cases where the borrow checker's static analysis is too conservative — e.g., graph data structures, observer pattern implementations, and mock objects in tests.