Box = exclusive ownership, heap allocation, no runtime overhead. Rc = shared ownership, heap allocation, reference counting overhead. Box is simpler and faster; Rc enables multiple owners.
Box — single owner:
1let boxed = Box::new(String::from("important"));2let taken = boxed; // Move ownership3println!("{}", taken); // important4// boxed is invalid here
Rc — shared ownership:
1use std::rc::Rc;23let shared = Rc::new(vec![10, 20, 30]);4let r1 = Rc::clone(&shared);5let r2 = Rc::clone(&shared);67// All three point to the same Vec8assert_eq!(shared[0], r1[0]);9assert_eq!(r1[1], r2[1]);10println!("Count: {}", Rc::strong_count(&shared)); // 3
When to use Box:
When to use Rc:
Common mistakes: