Box gives you exclusive ownership of heap data — one owner, immediate cleanup. Rc gives shared ownership — multiple owners, cleanup happens when the last owner drops.
Box — exclusive ownership:
1fn process(data: Box<Vec<i32>>) {2 println!("Processing {} items", data.len());3 // data is freed when function returns4}56let my_data = Box::new(vec![1, 2, 3, 4, 5]);7process(my_data); // Ownership moved into function8// my_data is no longer valid here
Rc — shared ownership:
1use std::rc::Rc;23struct SharedState {4 users: Vec<String>,5 max_connections: usize,6}78let state = Rc::new(SharedState {9 users: vec!["alice".into(), "bob".into()],10 max_connections: 100,11});1213let handler1 = Rc::clone(&state);14let handler2 = Rc::clone(&state);15let handler3 = Rc::clone(&state);1617// All handlers access the same SharedState18println!("Users: {}", handler1.users.len());19println!("Max: {}", handler2.max_connections);20println!("Refs: {}", Rc::strong_count(&state)); // 4
When to use Box:
When to use Rc:
Common mistakes: