Rust Smart Pointers: Box, Rc, Arc, and RefCell with Interior Mutability
Four pointers, four policies: single owner, shared single-thread, shared multi-thread, and a runtime borrow check. The cycles that leak and the panics that bite.

Quick Summary
Rust's smart pointers encode four different sharing and mutability policies. Box<T> is the simplest: one owner, heap allocation, no extra runtime cost beyond the indirection — its job is recursive types, trait objects, and moving large values without copying. Rc<T> adds shared ownership for single-threaded code by keeping a non-atomic reference count. Arc<T> is the thread-safe version, paying for atomic increments on every clone. RefCell<T> moves the borrow check from compile time to runtime, giving interior mutability behind a shared reference, at the cost of a panic if two mutable borrows overlap.
The combinations are the point. Rc<RefCell<T>> is the single-threaded shared-mutable graph. Arc<Mutex<T>> is the multi-threaded one. Rc<T> is not Send, so sharing it across threads is a compile error rather than a data race — the type system refuses the version that would be undefined behaviour.
Choose by the question you are answering. One owner: Box. Many owners, one thread: Rc. Many owners, many threads: Arc. Mutation through a shared reference, one thread, checked at runtime: RefCell (or Cell for Copy types). Everything else should be a plain value or a borrow.
Basic syntax and query signatures
// Box: heap allocation, single owner
let b: Box<i32> = Box::new(5);
println!("{}", *b + 1);
// Recursive type: without Box this is infinitely sized
enum List { Cons(i32, Box<List>), Nil }
// Trait object
let s: Box<dyn std::fmt::Display> = Box::new("hello");
println!("{s}");
// Rc: shared ownership, cloned by count
use std::rc::Rc;
let a = Rc::new(String::from("shared"));
let b = Rc::clone(&a); // or a.clone(), same thing
println!("{}", Rc::strong_count(&a)); // 2
drop(b);
println!("{}", Rc::strong_count(&a)); // 1
// Arc: same API, atomic
use std::sync::Arc;
let data = Arc::new(vec![1, 2, 3]);
let handle = {
let data = Arc::clone(&data);
std::thread::spawn(move || data.iter().sum::<i32>())
};
// RefCell: runtime borrow checking
use std::cell::RefCell;
let cell = RefCell::new(vec![1]);
cell.borrow_mut().push(2); // ok: no other borrow alive
println!("{:?}", cell.borrow());
// Cell: no borrows, whole-value get/set, only for Copy
use std::cell::Cell;
let c = Cell::new(1);
c.set(c.get() + 1);The composed forms, which is how these are used in practice:
// Single-threaded shared mutable state
let shared: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
shared.borrow_mut().push("a".into());
let sibling = Rc::clone(&shared);
sibling.borrow_mut().push("b".into());
// Thread-safe shared mutable state
use std::sync::Mutex;
let counter = Arc::new(Mutex::new(0u64));
for _ in 0..4 {
let c = Arc::clone(&counter);
std::thread::spawn(move || { *c.lock().unwrap() += 1; }).join().unwrap();
}
// Weak: a non-owning link that breaks cycles
use std::rc::Weak;
struct Node { next: RefCell<Option<Rc<Node>>>, parent: RefCell<Weak<Node>> }Key comparison table
| Pointer | Ownership | Thread safe | Clone cost | Borrow failure |
|---|---|---|---|---|
Box<T> | Single | If T: Send | Deep copy (T: Clone) | Compile time |
Rc<T> | Shared (count) | No (!Send) | Increment | Compile time (no &mut) |
Arc<T> | Shared (atomic count) | Yes (Send + Sync if T) | Atomic increment | Compile time (no &mut) |
RefCell<T> | Single | No (!Sync) | n/a | Panic at runtime |
Cell<T> | Single | No | n/a | None (no borrows) |
Weak<T> | None | Matches parent | Increment | n/a (upgrade may fail) |
Mutex<T> | Single wrapper | Yes (Sync) | n/a | Blocking, or poisoned |
| Need | Type |
|---|---|
| Heap value, one owner | Box<T> |
| Shared read-only across threads | Arc<T> |
| Shared read-only, one thread | Rc<T> |
| Shared mutable, one thread | Rc<RefCell<T>> |
| Shared mutable, threads | Arc<Mutex<T>> or Arc<RwLock<T>> |
| Cow-like clone-on-write sharing | Rc::make_mut / Arc::make_mut |
| Observer that must not keep the parent alive | Weak<T> |
Practical edge cases and deep dives
1. Rc cycles leak, and Weak is the fix
struct Node {
value: i32,
next: RefCell<Option<Rc<Node>>>,
parent: RefCell<Option<Rc<Node>>>, // cycle: parent -> child -> parent
}
let a = Rc::new(Node { value: 1, next: RefCell::new(None), parent: RefCell::new(None) });
let b = Rc::new(Node { value: 2, next: RefCell::new(None), parent: RefCell::new(None) });
*a.next.borrow_mut() = Some(Rc::clone(&b));
*b.parent.borrow_mut() = Some(Rc::clone(&a)); // strong count of both is now 2 foreverBoth counts never reach zero, so the memory is unreachable but never freed. Store the back-reference as Weak:
struct Node2 {
value: i32,
next: RefCell<Option<Rc<Node2>>>,
parent: RefCell<Weak<Node2>>, // non-owning
}
let p = Rc::new(Node2 { value: 1, next: RefCell::new(None), parent: RefCell::new(Weak::new()) });
let c = Rc::new(Node2 { value: 2, next: RefCell::new(None), parent: RefCell::new(Rc::downgrade(&p)) });
*c.parent.borrow_mut().upgrade() // Option<Rc<Node2>>: None once the parent is gone2. RefCell panics at the worst possible time
let c = RefCell::new(vec![1, 2, 3]);
let a = c.borrow();
let b = c.borrow_mut(); // thread 'main' panicked: already borrowed: BorrowMutErrorUnlike the compile-time check, the runtime check is not flow-sensitive across functions: a helper that borrows and a caller that also borrows produce a panic with no compile-time warning.
// Checked alternative: returns Result instead of panicking
if let Ok(mut v) = c.try_borrow_mut() { v.push(4); }
// Scope the borrow so it ends before the next one
{
let v = c.borrow();
println!("{}", v.len());
}
c.borrow_mut().push(4);The rules are the same as &/&mut, so a Ref held across a call that mutates the same cell is an immediate panic. Holdings across .await inside async code are a classic source of this, because another task polled on the same thread can reach the same cell.
3. Rc<RefCell<T>> cannot cross a thread boundary — by design
let shared = Rc::new(RefCell::new(0));
// std::thread::spawn(move || { *shared.borrow_mut() += 1; });
// error[E0277]: `Rc<RefCell<i32>>` cannot be sent between threads safelyThe compiler message names the missing auto traits (!Send, !Sync). Replacing Rc with Arc is not enough — RefCell is also !Sync — so the thread-safe form is Arc<Mutex<T>>. This is the type system preventing a data race rather than merely warning about one.
4. Box for recursive types and large moves
// Without indirection: error[E0072] recursive type has infinite size
// enum Tree { Node(Tree, Tree), Leaf }
enum Tree { Node(Box<Tree>, Box<Tree>), Leaf(i32) }
// Large struct: moving a 10 MB array by value copies it
let big = Box::new([0u8; 10 * 1024 * 1024]);
let moved = big; // moves the pointer, not the bytesBox is also what a dyn Trait in a struct needs, since trait objects have unknown size.
5. make_mut gives copy-on-write without a Mutex
let mut a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
// Not shared anymore: clones the value inside, so b keeps the old data
Rc::make_mut(&mut a).push(4);
assert_eq!(*b, vec![1, 2, 3]);
assert_eq!(*a, vec![1, 2, 3, 4]);
// Shared: mutates in place, both see the change
let mut c = Rc::new(vec![1]);
Rc::make_mut(&mut c).push(2); // strong_count == 1: no cloneArc::make_mut does the same atomically. This pattern is how immutable-by-convention APIs (configuration snapshots, persistent lists) avoid cloning the whole structure on every update.
6. Mutex poisoning and lock scope
let counter = Arc::new(Mutex::new(0));
{
let mut guard = counter.lock().unwrap(); // guard held until the block ends
*guard += 1;
} // unlocked here
// Poisoned after a panic while holding the lock
let guard = match counter.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(), // recover deliberately
};A MutexGuard is not Send, so holding one across .await is rejected by the compiler — usually the most useful error an async Rust beginner receives, since it prevents a deadlock that would be nearly impossible to reproduce.
7. When you do not need a smart pointer at all
fn total(items: &[u32]) -> u32 { items.iter().sum() } // borrow, no Rc
struct App { config: Config } // own it, no Box
// A struct that shares immutably can often take &T
fn render(cfg: &Config) -> String { /* ... */ }Rc appears in designs where ownership was not decided first: a service struct wraps everything in Rc<RefCell<_>> and then fights borrow panics. Prefer plain ownership plus borrows until you can name the specific sharing that requires a count.
Common mistakes and runtime errors
| Error / symptom | Cause | Fix |
|---|---|---|
E0072 recursive type has infinite size | Direct self-reference | Box, Rc, or Vec indirection |
BorrowMutError already borrowed | RefCell double borrow | Scope the borrow, use try_borrow_mut |
E0277 cannot be sent between threads safely | Rc/RefCell in a thread | Arc<Mutex<T>> |
E0277 cannot be shared between threads safely | RefCell behind Arc | Mutex/RwLock |
| Memory grows without bound | Rc cycle | Weak for back-references |
Rc::strong_count never drops | Cycle or captured clone | Find the cycle; use downgrade |
| Mutex deadlock | Two locks acquired in different orders | Consistent order, try_lock |
MutexGuard across .await rejected | Guard is !Send | Scope the lock, copy the value out |
| Slow clone in a hot loop | Arc atomic contention | Clone once, share by reference |
Cell<T> does not compile with a non-Copy type | Cell moves whole values | Use RefCell |
deref confusion on Box<Vec<T>> | Extra indirection | Box<[T]> or plain Vec |
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.