Box = one owner, heap data, immediate cleanup. Rc = many owners, heap data, reference-counted cleanup. Box is simpler and faster; Rc is more flexible for shared ownership.
Box — single owner:
1let boxed = Box::new(String::from("hello"));2let moved = boxed; // Ownership transferred3println!("{}", moved); // "hello"4// boxed is now invalid
Rc — multiple owners:
1use std::rc::Rc;23let shared = Rc::new(vec![1, 2, 3]);4let a = Rc::clone(&shared);5let b = Rc::clone(&shared);67// All three point to the same Vec8println!("{} {} {}", shared[0], a[1], b[2]); // 1 2 39println!("Count: {}", Rc::strong_count(&shared)); // 3
When to use Box:
When to use Rc:
Common mistakes: