Box is a heap-allocating smart pointer with strict single ownership — when it goes out of scope, the data is immediately freed. Rc (Reference Counted) allows multiple owners of the same heap data through reference counting — data is freed only when the last owner drops.
Box — single owner, immediate cleanup:
1fn create_list() -> Box<dyn std::fmt::Display> {2 Box::new("hello") // Returns trait object — size unknown at call site3}45let data = Box::new([0u8; 1024 * 1024]); // 1MB on heap6// Freed immediately when `data` goes out of scope
Rc — shared ownership, deferred cleanup:
1use std::rc::Rc;23#[derive(Debug)]4struct Config {5 name: String,6 timeout: u32,7}89let config = Rc::new(Config { name: "prod".into(), timeout: 30 });1011// Multiple parts of the app share the same config12let db_pool = Rc::clone(&config);13let cache = Rc::clone(&config);14let logger = Rc::clone(&config);1516println!("Config shared by {} components", Rc::strong_count(&config)); // 4
When to use Box:
Box<dyn Error>).When to use Rc:
Common mistakes: