Box = one owner, heap data, immediate cleanup, no overhead. Rc = many owners, heap data, reference-counted cleanup, small overhead. Box for exclusive; Rc for shared.
Box — exclusive ownership:
1fn create_node(value: i32) -> Box<dyn std::fmt::Display> {2 Box::new(value)3}45let node = create_node(42);6println!("{}", node); // 427// node is freed when it goes out of scope
Rc — shared ownership:
1use std::rc::Rc;23struct SharedConfig {4 debug_mode: bool,5 max_retries: u32,6}78let config = Rc::new(SharedConfig { debug_mode: true, max_retries: 3 });9let db = Rc::clone(&config);10let api = Rc::clone(&config);1112println!("Debug: {}", db.debug_mode); // true13println!("Retries: {}", api.max_retries); // 3
When to use Box:
When to use Rc:
Common mistakes: