Skip to content

Interior Mutability

Rust’s borrowing rules state that a shared reference (&T) is immutable — you cannot modify the Data through it. This is a compile-time guarantee that prevents data races and enables safe Concurrency. However, there are legitimate cases where you need to mutate data through a shared Reference. Interior mutability types provide this capability while maintaining safety guarantees.

The core tension: &T promises the caller that the data will not change, but sometimes the data Needs to change in response to operations that only have a shared reference available. Interior Mutability resolves this by moving the mutation check from compile time to runtime (for Single-threaded types) or by using synchronization primitives (for multi-threaded types).

UnsafeCell<T> is the foundation of all interior mutability in Rust. It is the only type in the Standard library that allows you to obtain a mutable reference to its interior through a shared Reference. All other interior mutability types (Cell``RefCell``Mutex``RwLock) are built on Top of UnsafeCell.

use std::cell::UnsafeCell;
struct Counter {
value: UnsafeCell<i32>,
}
impl Counter {
fn new(value: i32) -> Self {
Counter {
value: UnsafeCell::new(value),
}
}
fn increment(&self) {
unsafe {
*self.value.get() += 1;
}
}
fn get(&self) -> i32 {
unsafe { *self.value.get() }
}
}
## Intuition

Interior mutability lets you modify data through a shared reference, bypassing the usual borrowing rules at runtime. RefCell performs borrow checking at runtime, panicking on violations. Cell provides copyable values without borrow checks. Mutex and RwLock enable thread-safe interior mutability. This pattern is essential for building safe abstractions like caches, lazy initialization, and reference-counted shared state where compile-time checking is too restrictive.

  • [[rust/02-ownership-borrowing/ownership]] - Compile-time borrow checking rules
  • [[rust/02-ownership-borrowing/lifetimes]] - Lifetime constraints on mutable references
  • [[rust/06-concurrency/concurrency]] - Thread-safe mutability patterns
  • [[rust/03-structs-enums/structs-and-enums]] - Structs with RefCell fields