Smart Pointers in Rust

Smart pointers in Rust are types that act like pointers but have additional metadata and capabilities - usually around ownership and memory management.

The main ones:

Box<T> - heap allocation. Puts data on the heap instead of the stack. Useful for recursive types (where the size isn’t known at compile time) or when you want to transfer ownership without copying large data.

enum List {
    Cons(i32, Box<List>),
    Nil,
}

Rc<T> - reference counting. Multiple owners for the same data. The data is freed when the last Rc is dropped. Single-threaded only.

use std::rc::Rc;

let a = Rc::new(5);
let b = Rc::clone(&a);  // both a and b own the data

Arc<T> - atomic reference counting. Like Rc but thread-safe. Use this when you need shared ownership across threads.

RefCell<T> - interior mutability. Lets you mutate data even when you only have an immutable reference. The borrow rules are checked at runtime instead of compile time - you’ll get a panic if you violate them.

use std::cell::RefCell;

let x = RefCell::new(5);
*x.borrow_mut() += 1;  // mutate through an "immutable" binding

Mutex<T> and RwLock<T> - thread-safe interior mutability. Lock the data before accessing it. Mutex for exclusive access, RwLock when you want multiple readers.

The pattern: regular Rust ownership is strict but cheap. Smart pointers relax the rules in controlled ways, often with runtime cost (heap allocation, reference counting, locking). Pick the simplest one that solves your problem.