πŸ“¦

Box, Rc, Arc, RefCell β€” Smart Pointer Guide

Tools for flexibly working around ownership rules

Ownership rules are powerful but don't cover every pattern.

Box<T> β€” Allocates on the heap. Required for recursive types (linked lists, etc.). Also for types with unknown compile-time size.

Rc<T> β€” Reference Counted. For multiple owners. Value freed when last Rc drops. Single-thread only.

Arc<T> β€” Atomic Rc. Thread-safe shared ownership for multi-threaded contexts.

RefCell<T> β€” Runtime borrow checking. For patterns where compile-time safety can't be proven. Panics at runtime on misuse.

In practice, Arc<Mutex<T>> is very common β€” the standard pattern for shared mutable data across threads.

Key Points

1

Box<T> β€” heap allocation + ownership transfer (recursive types, trait objects)

2

Rc<T> / Arc<T> β€” reference-counted shared ownership (single/multi thread)

3

RefCell<T> β€” runtime borrow checking (Interior Mutability pattern)

4

Arc<Mutex<T>> β€” standard pattern for multi-thread shared mutable data

Pros

  • Safely implement patterns that ownership rules forbid
  • Rc/Arc provide automatic memory release without GC

Cons

  • Rc/Arc leak memory on circular references (use Weak)
  • RefCell can panic at runtime β€” compile-time safety sacrificed

Use Cases

Tree/graph data structures β€” shared references between nodes Concurrent servers β€” share state between requests via Arc<Mutex<State>>