Box is a smart pointer that provides single ownership of heap-allocated data. Rc (Reference Counted) is a smart pointer that allows multiple owners of the same heap-allocated data through reference counting.
Box — single ownership:
1let b = Box::new(5);2let b2 = b; // Ownership moves to b23// println!("{}", b); // Error! b is no longer valid4println!("{}", b2); // 5
Rc — multiple ownership:
1use std::rc::Rc;23let rc1 = Rc::new(vec![1, 2, 3]);4let rc2 = Rc::clone(&rc1); // Increments count5let rc3 = Rc::clone(&rc1); // Increments count again6println!("Count: {}", Rc::strong_count(&rc1)); // 37drop(rc3); // Decrements count to 28println!("Count: {}", Rc::strong_count(&rc1)); // 29// Data stays alive as long as rc1 or rc2 exist
When to use Box:
When to use Rc:
Common mistakes: