About

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>>
← Enum, Option, Result — Algebraic Data Types in Rust Threads & Channels — Ownership-Based Concurrency →