Box = single owner, heap allocation, no runtime cost. Rc = multiple owners, heap allocation, reference counting. Box is simpler; Rc is more flexible for shared data.
Box — exclusive ownership:
1let data = Box::new(vec![1, 2, 3]);2let moved = data; // Ownership moves3// data is no longer valid4println!("{:?}", moved); // [1, 2, 3]
Rc — shared ownership:
1use std::rc::Rc;23let shared = Rc::new(String::from("shared data"));4let owner1 = Rc::clone(&shared);5let owner2 = Rc::clone(&shared);67println!("{}", *shared); // shared data8println!("{}", *owner1); // shared data9println!("Refs: {}", Rc::strong_count(&shared)); // 3
When to use Box:
When to use Rc:
Common mistakes: