Cell and RefCell in Rust
(a practical guide to interior mutability)
Rust’s normal ownership + borrowing rules say:
- if you have
&T, the data is immutable
- if you have
&mut T, the data is mutable, but there can be no other live references
Those guarantees are checked at compile-time.
Sometimes, though, you really do need to mutate something even though other code only has an immutable reference. That pattern is called interior mutability.
Cell<T> and RefCell<T> are the two single-threaded building blocks that enable it.
1. Why are they needed?
-
Shared ownership that still needs mutation
Example: an Rc<T> counted pointer is by definition shared, so you can only get &T.
If the data must occasionally change (e.g. a lazily-computed cache) you need interior mutability.
-
Self-referential / cyclic data structures
You often build them with Rc<RefCell<T>>.
-
Library ergonomics
Exposing an immutable API while doing internal bookkeeping (counters, memoization, …).
-
Runtime checks instead of compile-time
The compiler can’t verify some borrowing patterns statically, so RefCell does it dynamically.
If you violate the rules, you get a panic at runtime, not a compile error.
2. Cell<T> vs RefCell<T> – what’s the difference?
| Feature | Cell<T> | RefCell<T> |
|---|
| Works with any type? | Only Copy or types you’re willing to move in/out | Any type (T: ?Sized) |
| How do you access data? | By value (get, set, replace) – never a reference | By borrowing (borrow() ⇒ Ref<T>, borrow_mut() ⇒ RefMut<T>) |
| Borrow checking | Compile-time trivial (no references) | Runtime; keeps a borrow counter |
| Overhead | Zero runtime overhead, just moves | Small runtime check; possible panic |
| Thread safety | !Sync / !Send (single thread only) | Same |
| Typical uses | Counters, flags, caching small Copy data | Complex structures, bigger payloads, graphs, ASTs |
Mental model
• Cell = “little box that you can swap values in and out of”.
• RefCell = “little box that hands out checked borrows at runtime”.
3. Quick code recipes
3.1 Cell<T> – mutate Copy data
use std::cell::Cell;
struct Player {
// Everyone else sees an immutable `Player`,
// but we still track how many times it's rendered.
render_count: Cell<u32>,
}
impl Player {
fn render(&self) {
let old = self.render_count.get();
self.render_count.set(old + 1);
// ...actual render...
}
}
Note:
get() copies out the value.
set(new) overwrites it.
- No refs are ever produced, so borrow rules are trivially upheld.
3.2 RefCell<T> – mutate non-Copy data
use std::cell::RefCell;
use std::rc::Rc;
type NodeRef = Rc<RefCell<Node>>;
#[derive(Default)]
struct Node {
value: String,
children: Vec<NodeRef>,
}
fn add_child(parent: &NodeRef, child: NodeRef) {
parent.borrow_mut().children.push(child);
}
fn print_value(node: &NodeRef) {
println!("{}", node.borrow().value);
}
fn main() {
let root = Rc::new(RefCell::new(Node {
value: "root".into(),
..Default::default()
}));
let leaf = Rc::new(RefCell::new(Node {
value: "leaf".into(),
..Default::default()
}));
add_child(&root, leaf);
print_value(&root);
}
Key points:
borrow() ⇒ immutable Ref<T> (read)
borrow_mut() ⇒ mutable RefMut<T> (write)
- If a mutable borrow is active, any new borrow will panic at runtime.
4. When should you reach for them?
Prefer normal &mut or ownership transfer whenever possible.
Use Cell/RefCell when:
- You only have
&T but must mutate internal state.
- You’re working in a single thread (they’re not
Sync nor Send).
- You accept possible runtime panics for mis-borrow (especially
RefCell).
- The design (e.g., shared graph, GUI tree) makes exclusive borrows awkward.
Rule of thumb:
Copy data -> Cell<T>
Non-Copy -> RefCell<T>
Multi-thread-> Mutex<T> / RwLock<T> / Atomic*
5. Best practices & gotchas
✅ Prefer Cell over RefCell when possible – simpler and zero-cost.
✅ Keep the mutable window short: drop RefMut ASAP.
✅ Wrap only the fields that need interior mutability, not the whole struct (Cell<Flag>, not Cell<WholeStruct>).
✅ Document that your type uses interior mutability; it can surprise maintainers.
✅ Provide high-level methods so callers don’t need to handle borrow_* directly.
⚠️ A RefCell panic = logic bug; fuzz / test for it.
⚠️ Don’t store Ref<'_, T> or RefMut<'_, T> outside the scope that created them.
⚠️ Rc<RefCell<T>> cycles leak memory (they never drop). Break cycles manually or use Weak.
⚠️ Not thread-safe. For cross-thread mutation use Mutex, RwLock, or Atomic*.
6. Summary cheat sheet
Interior mutability lets you mutate through &T.
Cell<T> | moves in/out, Copy types, zero overhead
RefCell<T> | runtime borrow checking, any type, may panic
Use them sparingly, document why they’re needed, and keep borrows short. When you do, they make certain patterns (caches, GUIs, graphs, self-referential structures) straightforward and safe in single-threaded Rust.