Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readRust
#Rust#Memory Management#Concurrency
3D illustration of heap Box containers, shared reference-counting rings and a RefCell borrow gate

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

rust
// 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:

rust
// 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

PointerOwnershipThread safeClone costBorrow failure
Box<T>SingleIf T: SendDeep copy (T: Clone)Compile time
Rc<T>Shared (count)No (!Send)IncrementCompile time (no &mut)
Arc<T>Shared (atomic count)Yes (Send + Sync if T)Atomic incrementCompile time (no &mut)
RefCell<T>SingleNo (!Sync)n/aPanic at runtime
Cell<T>SingleNon/aNone (no borrows)
Weak<T>NoneMatches parentIncrementn/a (upgrade may fail)
Mutex<T>Single wrapperYes (Sync)n/aBlocking, or poisoned
NeedType
Heap value, one ownerBox<T>
Shared read-only across threadsArc<T>
Shared read-only, one threadRc<T>
Shared mutable, one threadRc<RefCell<T>>
Shared mutable, threadsArc<Mutex<T>> or Arc<RwLock<T>>
Cow-like clone-on-write sharingRc::make_mut / Arc::make_mut
Observer that must not keep the parent aliveWeak<T>

Practical edge cases and deep dives

1. Rc cycles leak, and Weak is the fix

rust
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 forever

Both counts never reach zero, so the memory is unreachable but never freed. Store the back-reference as Weak:

rust
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 gone

2. RefCell panics at the worst possible time

rust
let c = RefCell::new(vec![1, 2, 3]); let a = c.borrow(); let b = c.borrow_mut(); // thread 'main' panicked: already borrowed: BorrowMutError

Unlike 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.

rust
// 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

rust
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 safely

The 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

rust
// 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 bytes

Box 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

rust
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 clone

Arc::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

rust
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

rust
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 / symptomCauseFix
E0072 recursive type has infinite sizeDirect self-referenceBox, Rc, or Vec indirection
BorrowMutError already borrowedRefCell double borrowScope the borrow, use try_borrow_mut
E0277 cannot be sent between threads safelyRc/RefCell in a threadArc<Mutex<T>>
E0277 cannot be shared between threads safelyRefCell behind ArcMutex/RwLock
Memory grows without boundRc cycleWeak for back-references
Rc::strong_count never dropsCycle or captured cloneFind the cycle; use downgrade
Mutex deadlockTwo locks acquired in different ordersConsistent order, try_lock
MutexGuard across .await rejectedGuard is !SendScope the lock, copy the value out
Slow clone in a hot loopArc atomic contentionClone once, share by reference
Cell<T> does not compile with a non-Copy typeCell moves whole valuesUse RefCell
deref confusion on Box<Vec<T>>Extra indirectionBox<[T]> or plain Vec

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.