Sub topic 17
Choosing between Box, Rc, RefCell, and the alternatives
This chapter assumes you know ownership, moves, and borrowing. It also assumes you have read the earlier chapters on Box<T>, Rc<T>, RefCell<T>, Weak<T>, and the Deref and Drop traits. Here you turn that material into a decision procedure. Each pointer type solves one problem. Picking the wrong one usually costs you a compile error, a runtime panic, or a leak.
Start with the default: no smart pointer
Most Rust code needs none of these types. A plain value on the stack, a Vec<T>, or a String already owns heap data. A &T or &mut T handles temporary access. Add a smart pointer only when a specific constraint forces you to. The constraints are:
- The compiler cannot know the size of a type.
- You need a value of an unknown concrete type.
- More than one owner must keep a value alive.
- You must mutate through a shared reference.
- The data crosses thread boundaries.
Ask these questions in order. Stop at the first one that applies.
What each type buys you
| Type | Owners | Borrow checking | Threads | Typical use |
|---|---|---|---|---|
| `Box<T>` | One | Compile time | Sendable if `T` is | Recursive types, `Box<dyn Trait>`, moving large values cheaply |
| `Rc<T>` | Many | Compile time (immutable only) | No | Shared read-only data, graph nodes |
| `RefCell<T>` | One | Runtime | No | Mutation behind `&T`, mocks, caches |
| `Cell<T>` | One | None needed (copies in and out) | No | Counters and flags of `Copy` types |
| `Arc<T>` | Many | Compile time (immutable only) | Yes | Shared read-only data across threads |
| `Mutex<T>` | One | Runtime (locking) | Yes | Mutation shared between threads |
| `Weak<T>` | None (non-owning) | Runtime (`upgrade`) | Matches `Rc` or `Arc` | Parent links, caches, observers |
Box: one owner, known size
Choose Box<T> when the value has a single owner and the problem is size or type. Use it in two cases:
- A recursive enum such as the cons list. The
Boxgives the compiler a pointer-sized field instead of an infinitely nested one. - A trait object such as
Box<dyn Shape>. TheBoxholds a value whose concrete type is only known at runtime.
Box adds no reference counts and no runtime checks. Its only cost is one heap allocation and an indirection on access. If you only want to avoid copying a large struct, passing &T is often enough. Use Box when you need ownership to move cheaply.
Rc: several owners, one thread
Choose Rc<T> when a value has no single obvious owner. Several parts of the program must keep it alive, and none of them outlives all the others in a predictable way. Typical examples are shared nodes in a graph and a configuration read by many components.
Remember three limits:
Rc<T>gives only&T. You cannot mutate through it directly.- The count is not atomic, so
Rc<T>is notSend. The compiler rejects sending it to another thread. - Cloning is cheap but not free. If one owner clearly outlives the rest, a plain reference is simpler and faster.
RefCell and Cell: mutation behind a shared reference
Interior mutability moves a check from compile time to runtime, or removes the need for one.
RefCell<T>works for anyT. It tracks borrows at runtime. A conflictingborrow_mutpanics, andtry_borrow_mutreturns anErrinstead.Cell<T>works by copying values in and out withgetandset. It never hands out references, so it cannot panic. ForCopytypes such as counters and flags it is the better choice.
RefCell moves the guarantee from the compiler to your tests. Programs that compile can still panic with already borrowed. Keep borrows short, and never hold a Ref or RefMut across a call that might borrow the same cell.
Combining them
The combinations below are common. Each one solves exactly two problems.
Rc<RefCell<T>>gives several owners who can all mutate, on one thread.Arc<Mutex<T>>gives the same on many threads.Mutex::lockblocks instead of panicking when another thread holds the lock.Arc<RwLock<T>>allows many concurrent readers or one writer. Use it when reads far outnumber writes.Box<RefCell<T>>is rarely useful. If there is one owner, ordinary&mutaccess usually works.Rc<Cell<T>>shares a smallCopyvalue, such as a flag, between owners.
Weak: owners and observers
Ownership edges should form a tree or a directed acyclic graph. When a link points back up, as with a child's parent or an observer's subject, make it a Weak<T>. That keeps the strong count from forming a cycle. The rule of thumb is that parents own children with Rc, and children refer to parents with Weak. Call upgrade each time you need the value. It returns None once all strong owners are gone, so handle that case.
Use Rc::strong_count and Rc::weak_count in tests to check that a structure is freed. A strong count that never reaches zero after you drop the owner points to a cycle.
Threads: the compiler decides
You do not need to remember which types are thread-safe, because the traits Send and Sync enforce it. Replace Rc with Arc and RefCell with Mutex or RwLock when the compiler reports that a type "cannot be sent between threads safely". Do not use the thread-safe types by default. Atomic reference counts and locks cost more than their single-threaded versions.
A worked example
This program uses Cell for a single-threaded counter and Arc<Mutex<_>> for a total updated by four threads.
use std::cell::Cell;
use std::sync::{Arc, Mutex};
use std::thread;
struct Hits {
count: Cell<u32>,
}
impl Hits {
fn record(&self) {
self.count.set(self.count.get() + 1);
}
}
fn main() {
let hits = Hits { count: Cell::new(0) };
hits.record();
hits.record();
println!("hits = {}", hits.count.get());
let total = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for i in 1..=4 {
let total = Arc::clone(&total);
handles.push(thread::spawn(move || {
*total.lock().unwrap() += i;
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("total = {}", *total.lock().unwrap());
}The program prints hits = 2 and then total = 10. record takes &self, yet it changes the count, because Cell allows that. Each thread gets its own Arc clone, and the mutex serializes the updates.
Common mistakes
- Using
Rc<RefCell<T>>everywhere. It hides ownership design problems and moves errors to runtime. Try restructuring with plain references or indices first. - Holding a
RefCellborrow too long. Aborrow_mutthat lives across a method call can cause a panic later, far from the cause. - Cloning the data when you meant to clone the pointer. Write
Rc::clone(&a). It states the intent and cannot be mistaken for a deep copy. - Strong links in both directions. This leaks memory silently, with no error.
- Locking a
Mutextwice in one thread. This can deadlock or panic. Keep the guard's scope small.
Exercises
Exercise
You are modeling a tree where each node owns its children and each child must be able to find its parent. The program is single-threaded and nodes are mutated after construction. Which types do you use for the child list and the parent link, and why?
Show answer
Use RefCell<Vec<Rc<Node>>> for the children and RefCell<Weak<Node>> for the parent. Rc lets the parent own each child, and RefCell allows adding children after construction through a shared reference. The parent link is Weak so that parent and child do not own each other, which would form a reference cycle and leak memory. The RefCell around the Weak lets you set the link after the parent exists.
Exercise
A struct holds a hits: u32 field, and a method taking &self must increment it. Which type should the field use, and when would you pick a different one?
Show answer
Use Cell<u32>, because u32 is Copy and Cell needs no borrow tracking and cannot panic. Pick RefCell if the field were not Copy, such as a Vec, and you needed to borrow its contents. Pick Mutex or an atomic type if the struct were shared between threads.