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.
Previous
What are associated types vs generic parameters in Rust traits?
Next
What are Rust's concurrency primitives (Send and Sync traits)?
More Rust Questions
View all →- Intermediate How does error handling with the ? operator work in Rust?
- Intermediate What are the thiserror and anyhow crates for error handling?
- Intermediate What are trait objects (dyn Trait) in Rust?
- Intermediate What are generics in Rust and how do where clauses work?
- Intermediate What are Rust smart pointers?