Interior Mutability in Rust
In Rust, an object that has interior mutability presents an immutable façade while internal states can get modified via references.
Rust disallow interior mutability by default but some types enable it. These types usually rely on additional runtime mechanisms or invariants to provide safe mutability. There normally fall into two categories:
- Types like Mutex or RefCell that ensures exclusivity with runtime mechanisms (only one
mut &
at a time)- Under the hood, these types relies on a type called UnsafeCell
- Types like
std::sync::atomic
and Cell do not give out a mutable reference to the inner value, but instead give methods to manipulating those values in place.
The concept of interior mutability is related to deep const-ness in C++.