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.
use std::cell::Cell; let c = Cell::new(1); c.set(c.get() + 1); // c is not declared `mut`
Try it
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.
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.
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
&mutcannot express your design. - RefCell panics, not blocks.
borrow_mut()while any other borrow is live panics with the messageRefCell already borrowed. Usetry_borrowandtry_borrow_mutto get aResultinstead. - 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 returnErr(PoisonError);unwrap()is common, but you can recover withinto_inner. - Deadlocks: locking the same
Mutextwice in one thread, or two threads locking two mutexes in opposite order, blocks forever. - Rc cycles leak.
Rc<RefCell<Node>>structures with parent links needWeakfor back pointers. - A
&Twith interior mutability changes the meaning of "immutable". Do not assume a&Statsis unchanged between calls. - Cost:
Cellis free,RefCelladds a counter check,Mutexis a system or user-space lock, atomics are the cheapest thread-safe option for single words.
Related
Cell,RefCell,Rc,Arc,SendandSync, Borrowing rules,std::sync- Tutorial: RefCell and Cell, Mutex and RwLock, Rc and Arc