Smart pointers are data structures that act like pointers but have additional metadata and capabilities.
Box<T> stores data on the heap instead of the stack:
let b = Box::new(5); // 5 is stored on the heap
println!("{}", b); // Deref coercion: prints 5Without Box, recursive types would have infinite size:
enum List {
Cons(i32, Box<List>),
Nil,
}This pattern is exactly how linked lists work! The Box gives us a known size (pointer size) at compile time.
| Type | Use Case |
|---|---|
Box<T> | Heap allocation, known size |
Rc<T> | Multiple ownership (single-threaded) |
Arc<T> | Multiple ownership (thread-safe) |
RefCell<T> | Interior mutability |
use std::rc::Rc;
let a = Rc::new(5);
let b = Rc::clone(&a); // Both point to same data
println!("count: {}", Rc::strong_count(&a)); // 2Implement sum_list that recursively sums all values in a cons list.
Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))) → 6Cons and Nil casesfn sum_list(list: &List) -> i32 {
match list {
Cons(value, next) => value + sum_list(next),
Nil => 0,
}
}