Rust Tutorial: Smart Pointers
Box<T> for heap allocation, Rc<T> for shared ownership, and RefCell<T> for interior mutability.
Pointers with power
Smart pointers are data structures that act like pointers but provide additional capabilities.
The most common: `Box<T>` (unique heap allocation), `Rc<T>` (shared ownership), `RefCell<T>` (runtime borrow checking).
What you'll learn in this Rust smart pointers tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 22 minutes.
- Box<T> — heap allocation — `Box<T>` stores a value on the heap. The Box itself lives on the stack.
- Recursive data with Box — A recursive type needs Box to have a known size at compile time.
- Rc<T> — shared ownership — `Rc<T>` (reference counted) allows multiple owners. The data is freed when the last Rc drops.
- RefCell<T> — interior mutability — `RefCell<T>` allows mutable borrows at runtime even through shared references.
- Rc<RefCell<T>> — shared mutable — Combine `Rc` and `RefCell` for shared mutable data.
- Box and Deref — Smart pointers implement `Deref` so you can use them like regular references.
- The Drop trait — Implement `Drop` to run code when a value goes out of scope.
- Weak<T> — avoid reference cycles — `Weak<T>` holds a non-owning reference — it does not prevent the data from being freed.
Rust Smart Pointers concepts covered
- Pointers with power