Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Concepts

Interior mutability in Rust

Reference for interior mutability in Rust: mutating through a shared reference with Cell, RefCell, OnceCell, Mutex, RwLock and atomics, and how checks move to run time.

Normally Rust forbids changing data behind a shared &T reference. Interior mutability is the controlled exception: a few standard types let you mutate their contents through &self, and enforce safety by some other means than the compile-time borrow checker. All of them are built on one primitive, UnsafeCell<T>, the only legal way to get a mutable pointer from a shared reference.

You reach for it when ownership is shared (Rc, Arc), when a method conceptually does not change observable state (caching, counters), or when the borrow structure is too dynamic to prove statically, such as a graph. The cost is that mistakes surface at run time, as a panic or a blocked thread, instead of a compile error.

Rust
use std::cell::Cell;
let c = Cell::new(1);
c.set(c.get() + 1);   // c is not declared `mut`

Try it

Rust Cell and RefCell

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Shared ownership with Rc and RefCell, and Mutex across threads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Violating RefCell's rules panics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The family of types

Type Threads How it stays safe Typical use
Cell<T> single never hands out references; get/set copy values counters, flags, small Copy data
RefCell<T> single tracks borrows at run time and panics on conflict shared mutable structures with Rc
OnceCell<T> / OnceLock<T> single / multi can be set only once lazy initialization
Mutex<T> multi one lock() guard at a time; others wait shared state across threads
RwLock<T> multi many readers or one writer read-heavy shared state
Atomic* multi hardware atomic instructions counters and flags

Cell and RefCell are !Sync: a shared reference to one cannot cross threads, so the compiler rejects using them from several threads. Mutex, RwLock and atomics are Sync.

Usage notes

  • Prefer plain borrowing first. Reach for interior mutability only when &mut cannot express your design.
  • RefCell panics, not blocks. borrow_mut() while any other borrow is live panics with the message RefCell already borrowed. Use try_borrow and try_borrow_mut to get a Result instead.
  • Keep borrows short. Guards (Ref, RefMut, MutexGuard) hold the borrow until dropped, so avoid holding one across a call that may borrow the same cell again.
  • Mutex poisoning: if a thread panics while holding the lock, later lock() calls return Err(PoisonError); unwrap() is common, but you can recover with into_inner.
  • Deadlocks: locking the same Mutex twice in one thread, or two threads locking two mutexes in opposite order, blocks forever.
  • Rc cycles leak. Rc<RefCell<Node>> structures with parent links need Weak for back pointers.
  • A &T with interior mutability changes the meaning of "immutable". Do not assume a &Stats is unchanged between calls.
  • Cost: Cell is free, RefCell adds a counter check, Mutex is a system or user-space lock, atomics are the cheapest thread-safe option for single words.