Sub topic 17
Choosing between Box, Rc, RefCell, and the alternatives
This chapter assumes you have read the earlier chapters on Box<T>, Rc<T>, RefCell<T>, Cell<T>, Weak<T>, Arc<T>, and Mutex<T>. It gives you a way to pick among them. It does not introduce new types.
Two questions decide most cases
Ask these in order.
- How many owners does the value need? One owner points to
Box<T>or a plain value. Several owners in one thread point toRc<T>. Several owners across threads point toArc<T>. - Does the value need to change through a shared reference? If not, you are done. If so, choose an interior mutability type:
Cell<T>,RefCell<T>, orMutex<T>.
100%
Comparing the types
| Type | Owners | Borrow checking | Thread-safe | Typical use |
|---|---|---|---|---|
| `Box<T>` | One | Compile time | If `T` is | Recursive types, trait objects, large values |
| `Rc<T>` | Many | Compile time (immutable only) | No | Shared read-only data, graphs |
| `RefCell<T>` | One | Runtime | No | Mutation behind `&T` |
| `Cell<T>` | One | None needed, values are copied in and out | No | Small `Copy` values such as counters |
| `Arc<T>` | Many | Compile time (immutable only) | Yes | Sharing across threads |
| `Mutex<T>` | One | Runtime lock | Yes | Mutation across threads |
Rules of thumb
- Start with plain values and references. Reach for a smart pointer only when the compiler or your design asks for one.
- Use
Box<T>when the size is unknown at compile time or you needBox<dyn Trait>. - Prefer
Cell<T>overRefCell<T>for smallCopyvalues. It has no borrow state and cannot panic. - Use
Rc<RefCell<T>>sparingly. Everyborrow_mutis a possible panic that the compiler cannot catch. - Use
Weak<T>for links that point back toward an owner, such as a child's parent pointer. - Switch to
ArcandMutexonly when threads are involved.RcandRefCellare notSendorSync, so the compiler rejects them across threads. Atomic counters makeArcslightly slower thanRc.
Common errors
- Panicking with
already borrowed. TwoRefCellborrows overlapped at runtime. Keep borrows short and drop them early. - Leaking memory with
Rccycles. Two nodes hold strong references to each other, so the count never reaches zero. Make one directionWeak. - Using
Rcwhere a reference would do. If one owner outlives all users, a plain&Tis cheaper and clearer.
Exercise
A single-threaded program keeps a shared list of log messages. Several components must read it, and one component must append to it. Which type do you use, and what changes if the components move to separate threads?
Show answer
Use Rc<RefCell<Vec<String>>>. Rc gives several owners and RefCell allows appending through a shared handle. With separate threads, use Arc<Mutex<Vec<String>>>, because Rc and RefCell are not thread-safe.