medium.com 5 min read Original Source

Let’s Learn Rust 010: Smart Pointers

In C you manage memory with raw pointers. In Java and Python you never think about it because the garbage collector handles everything. Rust takes a different path. You manage memory explicitly, but the language gives you tools that make it safe and predictable. Those tools are smart pointers.

When I first came across Box, Rc, and RefCell I thought they were edge cases you rarely use. I was wrong. They come up constantly once you start building anything non-trivial. This article explains what each one does and more importantly when and why you would reach for it.

1. What Is a Smart Pointer?

A smart pointer is a data structure that acts like a pointer but also has additional capabilities. In Rust, smart pointers implement two key traits:

  • Deref which lets you use the smart pointer like a regular reference.
  • Drop which runs cleanup code when the value goes out of scope.

You have already been using smart pointers. String is a smart pointer to heap-allocated text. Vec<T> is a smart pointer to a heap-allocated array. The ones in this article give you finer control over ownership and memory layout.

2. Box: Allocating on the Heap

By default, Rust values live on the stack. Box<T> lets you put a value on the heap and keep a pointer to it on the stack.

fn main() {
    let x = Box::new(5); // 5 is on the heap
    println!("{}", x);   // Deref lets you use it like a regular value
} // Box is dropped here, heap memory is freed automatically
fn main() {
    let x = Box::new(5); // 5 is on the heap
    println!("{}", x);   // Deref lets you use it like a regular value
} // Box is dropped here, heap memory is freed automatically

This looks simple, but Box solves a real problem. Consider a recursive type. A type that contains itself:

// This does NOT compile
enum List {
    Cons(i32, List), // ERROR: recursive type has infinite size
    Nil,
}
// This does NOT compile
enum List {
    Cons(i32, List), // ERROR: recursive type has infinite size
    Nil,
}

Rust cannot know the size of List at compile time because List contains List which contains List infinitely. The fix:

<button data-code="enum List {
Cons(i32, Box), // Box has a fixed size (pointer)
Nil,
}

fn main() {
let list = List::Cons(1,
Box::new(List::Cons(2,
Box::new(List::Cons(3,
Box::new(List::Nil))))));
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

enum List {
    Cons(i32, Box<List>), // Box has a fixed size (pointer)
    Nil,
}

fn main() {
    let list = List::Cons(1,
        Box::new(List::Cons(2,
            Box::new(List::Cons(3,
                Box::new(List::Nil))))));
}
enum List {
    Cons(i32, Box<List>), // Box has a fixed size (pointer)
    Nil,
}

fn main() {
    let list = List::Cons(1,
        Box::new(List::Cons(2,
            Box::new(List::Cons(3,
                Box::new(List::Nil))))));
}

Box<List> is just a pointer. Pointers have a known, fixed size. Problem solved.

In C++ you would use std::unique_ptr for the same job. Same concept, cleaner syntax in Rust.

The other common use for Box is trait objects, which let you store different types that share a trait behind a single pointer:

<button data-code="trait Animal {
fn speak(&self);
}

struct Dog;
struct Cat;
impl Animal for Dog {
fn speak(&self) { println!("Woof!"); }
}
impl Animal for Cat {
fn speak(&self) { println!("Meow!"); }
}
fn main() {
let animals: Vec<Box> = vec![
Box::new(Dog),
Box::new(Cat),
];
for animal in &animals {
animal.speak();
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

trait Animal {
    fn speak(&self);
}

struct Dog;
struct Cat;
impl Animal for Dog {
    fn speak(&self) { println!("Woof!"); }
}
impl Animal for Cat {
    fn speak(&self) { println!("Meow!"); }
}
fn main() {
    let animals: Vec<Box<dyn Animal>> = vec![
        Box::new(Dog),
        Box::new(Cat),
    ];
    for animal in &animals {
        animal.speak();
    }
}
trait Animal {
    fn speak(&self);
}

struct Dog;
struct Cat;
impl Animal for Dog {
    fn speak(&self) { println!("Woof!"); }
}
impl Animal for Cat {
    fn speak(&self) { println!("Meow!"); }
}
fn main() {
    let animals: Vec<Box<dyn Animal>> = vec![
        Box::new(Dog),
        Box::new(Cat),
    ];
    for animal in &animals {
        animal.speak();
    }
}

Box<dyn Animal> is how you achieve the equivalent of polymorphism you get for free in Java or Python. You are paying for it explicitly here, but you know exactly what the cost is.

3. Rc: Reference Counting

Box<T> gives one owner. What if you genuinely need multiple parts of your code to own the same data? That is what Rc<T> is for. Rc stands for Reference Counted.

use std::rc::Rc;

fn main() {
    let shared = Rc::new(String::from("shared value"));
    let a = Rc::clone(&shared);
    let b = Rc::clone(&shared);
    println!("shared: {}", shared);
    println!("a: {}", a);
    println!("b: {}", b);
    println!("count: {}", Rc::strong_count(&shared)); // 3
} // count drops to 0, memory freed
use std::rc::Rc;

fn main() {
    let shared = Rc::new(String::from("shared value"));
    let a = Rc::clone(&shared);
    let b = Rc::clone(&shared);
    println!("shared: {}", shared);
    println!("a: {}", a);
    println!("b: {}", b);
    println!("count: {}", Rc::strong_count(&shared)); // 3
} // count drops to 0, memory freed

Rc::clone does not clone the data. It creates another pointer to the same data and increments the reference count. When the count reaches zero, the memory is freed.

This is how Python and Java manage memory internally for most objects. The difference is in those languages the runtime does the counting for you invisibly. In Rust you are opting in explicitly.

One important limit: Rc<T> is for single-threaded code only. For multi-threaded code you use Arc<T> which was covered in the threads article. The difference is Arc uses atomic operations to update the count safely across threads, which costs a bit more performance.

4. RefCell: Interior Mutability

This one confused me the most when I started. Here is the problem it solves.

Rust’s borrowing rules say you can have either one mutable reference or any number of immutable references, but never both at the same time. These rules are checked at compile time. RefCell<T> moves that check to runtime.

use std::cell::RefCell;

fn main() {
    let data = RefCell::new(vec![1, 2, 3]);
    {
        let mut v = data.borrow_mut(); // mutable borrow
        v.push(4);
    } // mutable borrow ends here
    println!("{:?}", data.borrow()); // immutable borrow: [1, 2, 3, 4]
}
use std::cell::RefCell;

fn main() {
    let data = RefCell::new(vec![1, 2, 3]);
    {
        let mut v = data.borrow_mut(); // mutable borrow
        v.push(4);
    } // mutable borrow ends here
    println!("{:?}", data.borrow()); // immutable borrow: [1, 2, 3, 4]
}

.borrow() gives an immutable reference. .borrow_mut() gives a mutable reference. If you try to hold both at the same time, it panics at runtime instead of failing at compile time.

Why would you want this? The main use case is interior mutability. Situations where you need to mutate something inside a struct that is otherwise immutable.

<button data-code="use std::cell::RefCell;

struct Logger {
messages: RefCell<Vec>,
}
impl Logger {
fn new() -> Self {
Logger { messages: RefCell::new(vec![]) }
}
fn log(&self, msg: &str) { // takes &self, not &mut self
self.messages.borrow_mut().push(msg.to_string());
}
fn print_all(&self) {
for msg in self.messages.borrow().iter() {
println!("{}", msg);
}
}
}
fn main() {
let logger = Logger::new();
logger.log("first message");
logger.log("second message");
logger.print_all();
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

use std::cell::RefCell;

struct Logger {
    messages: RefCell<Vec<String>>,
}
impl Logger {
    fn new() -> Self {
        Logger { messages: RefCell::new(vec![]) }
    }
    fn log(&self, msg: &str) { // takes &self, not &mut self
        self.messages.borrow_mut().push(msg.to_string());
    }
    fn print_all(&self) {
        for msg in self.messages.borrow().iter() {
            println!("{}", msg);
        }
    }
}
fn main() {
    let logger = Logger::new();
    logger.log("first message");
    logger.log("second message");
    logger.print_all();
}
use std::cell::RefCell;

struct Logger {
    messages: RefCell<Vec<String>>,
}
impl Logger {
    fn new() -> Self {
        Logger { messages: RefCell::new(vec![]) }
    }
    fn log(&self, msg: &str) { // takes &self, not &mut self
        self.messages.borrow_mut().push(msg.to_string());
    }
    fn print_all(&self) {
        for msg in self.messages.borrow().iter() {
            println!("{}", msg);
        }
    }
}
fn main() {
    let logger = Logger::new();
    logger.log("first message");
    logger.log("second message");
    logger.print_all();
}

log takes &self (immutable reference) but still mutates the internal Vec. This is the pattern. The outside world sees an immutable Logger. Internally it can update itself.

In Java or Python, everything is mutable by default so you never need this pattern. In Rust, when you want selective mutability inside an otherwise immutable type, RefCell is the tool.

5. Combining Rc and RefCell

This combination comes up enough that it is worth seeing directly. Rc<RefCell<T>> lets you have multiple owners that can all mutate the shared data:

use std::cell::RefCell;
use std::rc::Rc;

fn main() {
    let shared = Rc::new(RefCell::new(vec![1, 2, 3]));
    let a = Rc::clone(&shared);
    let b = Rc::clone(&shared);
    a.borrow_mut().push(4);
    b.borrow_mut().push(5);
    println!("{:?}", shared.borrow()); // [1, 2, 3, 4, 5]
}
use std::cell::RefCell;
use std::rc::Rc;

fn main() {
    let shared = Rc::new(RefCell::new(vec![1, 2, 3]));
    let a = Rc::clone(&shared);
    let b = Rc::clone(&shared);
    a.borrow_mut().push(4);
    b.borrow_mut().push(5);
    println!("{:?}", shared.borrow()); // [1, 2, 3, 4, 5]
}

a and b both point to the same Vec. Both can mutate it. The reference count ensures the memory lives as long as any owner does. The RefCell ensures only one mutable borrow happens at a time.

For multi-threaded code, the equivalent is Arc<Mutex<T>> which you already know from the threads article.

6. Deref Coercion

When Rust sees a smart pointer where a reference is expected, it automatically dereferences it through the Deref trait. This is why you can pass a Box<String> where a &str is expected:

<button data-code="fn print_name(name: &str) {
println!("Hello, {}!", name);
}

fn main() {
let boxed_name = Box::new(String::from("Alice"));
print_name(&boxed_name); // Box → &String → &str, automatically
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn print_name(name: &str) {
    println!("Hello, {}!", name);
}

fn main() {
    let boxed_name = Box::new(String::from("Alice"));
    print_name(&boxed_name); // Box<String> → &String → &str, automatically
}
fn print_name(name: &str) {
    println!("Hello, {}!", name);
}

fn main() {
    let boxed_name = Box::new(String::from("Alice"));
    print_name(&boxed_name); // Box<String> → &String → &str, automatically
}

Rust follows the chain of Deref implementations until it finds the right type. This works across any number of smart pointer layers. You rarely think about it explicitly but it is why things just work when you mix smart pointers with regular references.

7. Drop and Cleanup

Every smart pointer implements Drop to run cleanup code. You can implement it on your own types too:

struct Resource {
    name: String,
}
impl Drop for Resource {
    fn drop(&mut self) {
        println!("Releasing resource: {}", self.name);
    }
}
fn main() {
    let r1 = Resource { name: String::from("database connection") };
    let r2 = Resource { name: String::from("file handle") };
    println!("Resources created");
} // r2 is dropped first, then r1 (reverse order of creation)
struct Resource {
    name: String,
}
impl Drop for Resource {
    fn drop(&mut self) {
        println!("Releasing resource: {}", self.name);
    }
}
fn main() {
    let r1 = Resource { name: String::from("database connection") };
    let r2 = Resource { name: String::from("file handle") };
    println!("Resources created");
} // r2 is dropped first, then r1 (reverse order of creation)

In C++ this is the destructor. In Java there is finalize() but it is unreliable and deprecated. In Python there is __del__ but the timing is unpredictable with the garbage collector. In Rust, Drop runs at a deterministic point: when the value goes out of scope. You can rely on it.

This is the basis of the RAII pattern (Resource Acquisition Is Initialization) that C++ popularized. Rust builds the entire memory management model on it.

Summary

Box<T> puts data on the heap. Use it for recursive types, large data you want to pass around cheaply, and trait objects. Rc<T> gives multiple ownership through reference counting for single-threaded code. RefCell<T> moves borrow checking to runtime and enables interior mutability. Rc<RefCell<T>> combines both for shared mutable ownership in single-threaded code.

The mental model I find most useful: each smart pointer is a trade-off. Box trades stack allocation for heap allocation. Rc trades single ownership for shared ownership at the cost of reference counting overhead. RefCell trades compile-time checking for runtime checking at the cost of panic risk.

What’s Next

We go into Lifetimes. Not just the syntax, but the mental model behind why they exist and how to think about them. After this article lifetimes will stop feeling like random compiler noise and start making actual sense.

Happy coding and safe assembling!

Follow this series and join us in mastering Rust from scratch!