Smart Pointers Basics
8 examples - 5 basic, 3 intermediate - for smart pointer types.
Prerequisites
Basic Examples
1. Box<T> Heap Allocation
fn main() {
let b = Box::new(42);
println!("{}", *b);
}Single owner heap pointer.
2. Rc<T> Shared Ownership
use std::rc::Rc;
let a = Rc::new(String::from("shared"));
let b = Rc::clone(&a);Reference counting - single thread.
3. Arc<T> Thread-Safe Shared
use std::sync::Arc;
let a = Arc::new(vec![1, 2]);Send + Sync atomic refcount.
4. RefCell<T> Interior Mutability
use std::cell::RefCell;
let c = RefCell::new(0);
*c.borrow_mut() += 1;Runtime borrow check - panics on violation.
5. Cow<'a, T> Clone-on-Write
use std::borrow::Cow;
let s: Cow<str> = Cow::Borrowed("hello");Borrow until mutation forces owned copy.
Intermediate Examples
6. Rc<RefCell<T>>
use std::rc::{Rc, RefCell};
let v = Rc::new(RefCell::new(vec![1]));
v.borrow_mut().push(2);Graphs in single-threaded code.
7. Weak<T> Breaking Cycles
use std::rc::{Rc, Weak};
// upgrade() returns Option<Rc<T>>8. Custom Deref
use std::ops::Deref;
struct MyBox<T>(T);
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T { &self.0 }
}Related: Smart Pointers Best Practices
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.