When to Use Box vs Rc vs Arc in Rust

Use Box for single ownership on the heap, Rc for shared ownership in one thread, and Arc for shared ownership across threads.

Use Box<T> for heap allocation with single ownership, Rc<T> for shared ownership in single-threaded code, and Arc<T> for shared ownership across threads. Box<T> ensures a known size on the stack while storing data on the heap. Rc<T> tracks reference counts to manage memory when multiple owners exist. Arc<T> provides thread-safe reference counting for concurrent programs.

use std::rc::Rc;
use std::sync::Arc;

// Single owner, heap allocated
let boxed = Box::new(5);

// Shared ownership, single thread
let rc = Rc::new(5);
let rc_clone = Rc::clone(&rc);

// Shared ownership, multi-threaded
let arc = Arc::new(5);
let arc_clone = Arc::clone(&arc);