Rust Smart Pointers Explained

Smart pointers in Rust provide additional functionality beyond regular references (&T), such as heap allocation, reference counting, interior mutability, and thread safety.

Box: Heap Allocation and Ownership

What is Box?

How to Use Box

fn main() {
    let x = Box::new(5); // `x` stores the heap-allocated value 5
    println!("x = {}", x);
}

Use Box when:

Don’t use Box when:

Rc: Multiple Owners (Reference Counting)

What is Rc?

How to Use Rc

use std::rc::Rc;

fn main() {
    let a = Rc::new(10);
    let b = Rc::clone(&a); // Increases reference count
    let c = Rc::clone(&a);

    println!("Reference count: {}", Rc::strong_count(&a)); // Prints: 3
}

Use Rc when:

Don’t use Rc when:

Arc: Thread-Safe Reference Counting

What is Arc?

How to Use Arc

use std::sync::Arc;
use std::thread;

fn main() {
    let a = Arc::new(10);
    let b = Arc::clone(&a);

    let handle = thread::spawn(move || {
        println!("Thread value: {}", b);
    });

    handle.join().unwrap();
}

Use Arc when:

Don’t use Arc when:

RefCell: Interior Mutability (Runtime Borrow Checking)

What is RefCell?

How to Use RefCell

use std::cell::RefCell;

fn main() {
    let a = RefCell::new(5);
    *a.borrow_mut() += 10;
    println!("Updated value: {}", a.borrow());
}

Use RefCell when:

Don’t use RefCell when:

Mutex: Thread-Safe Interior Mutability

What is Mutex<T>?

How to Use Mutex

use std::sync::{Mutex, Arc};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Final count: {}", *counter.lock().unwrap());
}

Use Mutex when:

Don’t use Mutex when:

Summary Table: Choosing the Right Smart Pointer

Smart PointerOwnershipThread-Safe?Mutable Access?Use Case
BoxSingleYesNoHeap allocation, recursive types
RcMultiple (reference counting)NoNoMultiple owners in single-threaded programs
ArcMultiple (atomic reference counting)YesNoMultiple owners in multi-threaded programs
RefCellSingleNoYes (interior mutability)Mutable access in single-threaded programs
MutexSingleYesYesMutable access in multi-threaded programs