Box = one owner, heap data, immediate cleanup, no overhead. Rc = many owners, heap data, reference-counted cleanup, small overhead. Box for exclusive ownership; Rc for shared.
Box — single owner:
1fn process(data: Box<dyn std::fmt::Display>) {2 println!("Data: {}", data);3 // data freed when function returns4}56let value = Box::new(42);7process(value); // value moved, now invalid
Rc — shared ownership:
1use std::rc::Rc;23struct SharedBuffer {4 data: Vec<u8>,5}67let buf = Rc::new(SharedBuffer { data: vec![0; 1024] });8let reader1 = Rc::clone(&buf);9let reader2 = Rc::clone(&buf);1011println!("Buffer size: {}", reader1.data.len()); // 102412println!("Refs: {}", Rc::strong_count(&buf)); // 3
When to use Box:
When to use Rc:
Common mistakes: