Sub topic 1
Rust Smart Pointers: Ownership and Borrowing
Prerequisites
Assume you know Rust ownership, moves, borrowing, lifetimes, structs, enums, pattern matching, traits, generics, and the basic difference between stack and heap memory.
Ownership and borrowing: the rules smart pointers bend
Rust normally gives each value one owner. Borrowing lets other code temporarily use that value through &T or &mut T, while the compiler checks that references remain valid and that mutable access is exclusive.
A smart pointer is a type that owns or manages another value and provides pointer-like behavior. Unlike a plain reference, it can define how the value is stored, shared, accessed, or cleaned up. Smart pointers still follow ownership rules, but they add controlled alternatives.
What makes a pointer smart
A smart pointer usually stores a value or an address and implements methods or traits that manage it. Common examples include:
Box<T>for heap allocation and ownership.Rc<T>for shared ownership in one thread.RefCell<T>for runtime-checked borrowing.
A smart pointer is still an ordinary Rust value. Moving it moves its ownership, and dropping it can release the managed data.
`Box<T>`: putting a value on the heap
Box<T> owns a T stored on the heap. The box itself is usually a small pointer-sized value on the stack. It is useful when a value is large, must have a stable address, or has a recursive type.
Recursive types: a cons list with `Box`
A recursive type contains another value of the same type. Direct recursion would have an unknown size, because the compiler could not determine where the value ends. Box supplies a known-size pointer:
use List::{Cons, Nil};
enum List {
Cons(i32, Box<List>),
Nil,
}
fn main() {
let list = Cons(1, Box::new(Cons(2, Box::new(Nil))));
println!("{list:?}");
}`Box<dyn Trait>`: values behind one interface
A trait object, written dyn Trait, allows dynamic dispatch through a shared interface. Box<dyn Trait> can own values of different concrete types:
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 { self.0 * self.0 }
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0))];
println!("{:.1}", shapes[0].area());
}`Deref`: treating a smart pointer like a reference
Implementing Deref lets a type respond to *value and enables deref coercion. Rust can automatically turn &MyBox<String> into &String, then into &str when a function needs it.
use std::ops::Deref;
struct MyBox<T>(T);
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}Exercise
Why does a recursive enum need Box<List> instead of List directly?
Show answer
Box stores the nested list behind a fixed-size pointer, allowing the enum itself to have a known size.