TExcelTAD
Home › Rust › Rust Smart Pointers

Rust Smart Pointers

A smart pointer is a value that acts like a pointer to some data but also carries extra abilities, such as owning heap memory, counting how many owners exist, or allowing changes that the borrow checker would normally forbid. You have already met two of them: String and Vec<T> both own heap memory and free it automatically. This chapter covers the three you will reach for most often.

Smart pointer Purpose
Box<T> Put a value on the heap with a single owner
Rc<T> Share ownership of a value between several owners (single thread)
RefCell<T> Mutate data through a shared reference, checked at run time

Box<T>: values on the heap

Box::new(value) moves the value onto the heap and gives you a small pointer on the stack. You use the box just like the value itself; it is freed when the box goes out of scope.

The classic reason to use a box is a recursive type. A type that contains itself directly would have infinite size, but a box has a fixed size (one pointer), so the compiler is happy.

rust · try it yourself
#[derive(Debug)]
enum Chain {
    Link(i32, Box<Chain>),
    End,
}

use Chain::{End, Link};

fn total(chain: &Chain) -> i32 {
    match chain {
        Link(value, next) => value + total(next),
        End => 0,
    }
}

fn main() {
    let boxed_number = Box::new(41);
    println!("boxed + 1 = {}", *boxed_number + 1);

    let list = Link(3, Box::new(Link(5, Box::new(Link(9, Box::new(End))))));
    println!("{:?}", list);
    println!("sum = {}", total(&list));
}
boxed + 1 = 42
Link(3, Link(5, Link(9, End)))
sum = 17

*boxed_number dereferences the box to reach the value inside. Boxes are also how you store trait objects, e.g. Box<dyn Shape>.

Rc<T>: shared ownership

Normally a value has exactly one owner. Sometimes, though, several parts of a program genuinely need to own the same data — for example two playlists that contain the same song. Rc<T> (reference counted) keeps a count of owners and frees the data only when the last one is dropped.

rust · try it yourself
use std::rc::Rc;

struct Song {
    title: String,
}

fn main() {
    let song = Rc::new(Song { title: String::from("Blue Skies") });
    println!("owners after creating: {}", Rc::strong_count(&song));

    let morning_mix = vec![Rc::clone(&song)];
    println!("owners after morning mix: {}", Rc::strong_count(&song));

    {
        let road_trip = vec![Rc::clone(&song)];
        println!("owners inside block: {}", Rc::strong_count(&song));
        println!("road trip plays '{}'", road_trip[0].title);
    }

    println!("owners after block: {}", Rc::strong_count(&song));
    println!("morning mix plays '{}'", morning_mix[0].title);
}
owners after creating: 1
owners after morning mix: 2
owners inside block: 3
road trip plays 'Blue Skies'
owners after block: 2
morning mix plays 'Blue Skies'

Rc::clone does not copy the song; it just bumps the counter. Data inside an Rc is read-only, because many owners might be looking at it.

Note: Rc<T> is for a single thread. For sharing between threads use its thread-safe sibling Arc<T>, covered in the Concurrency chapter.

RefCell<T>: interior mutability

The borrow checker enforces "many readers or one writer" at compile time. RefCell<T> moves that check to run time, so you can mutate data even when you only hold a shared reference to it. You call .borrow() for read access and .borrow_mut() for write access.

rust · try it yourself
use std::cell::RefCell;

struct Logger {
    lines: RefCell<Vec<String>>,
}

impl Logger {
    // Note: &self, not &mut self
    fn log(&self, msg: &str) {
        self.lines.borrow_mut().push(msg.to_string());
    }
}

fn main() {
    let logger = Logger { lines: RefCell::new(Vec::new()) };
    logger.log("starting");
    logger.log("loading data");
    logger.log("done");

    for (i, line) in logger.lines.borrow().iter().enumerate() {
        println!("{}: {}", i + 1, line);
    }
}
1: starting
2: loading data
3: done

If you break the rules at run time — for example by calling borrow_mut() while a borrow() is still alive — the program panics instead of failing to compile. Keep borrows short to stay safe.

Combining Rc and RefCell

Rc<RefCell<T>> is a common pattern: many owners, and any of them may change the shared value.

rust · try it yourself
use std::cell::RefCell;
use std::rc::Rc;

fn main() {
    let scoreboard = Rc::new(RefCell::new(0));

    let player_a = Rc::clone(&scoreboard);
    let player_b = Rc::clone(&scoreboard);

    *player_a.borrow_mut() += 10;
    *player_b.borrow_mut() += 25;
    *player_a.borrow_mut() += 5;

    println!("final score: {}", scoreboard.borrow());
    println!("owners: {}", Rc::strong_count(&scoreboard));
}
final score: 40
owners: 3

Tip: Reach for smart pointers only when plain ownership and borrowing don't fit. Most Rust code needs nothing more than Box now and then.

Test yourself

Why is Box needed in a recursive enum like enum List { Node(i32, Box<List>), Nil }?

  1. To make the list thread-safe
  2. To give the type a known, finite size
  3. To allow multiple owners
  4. To make the values mutable

What does Rc::clone(&x) do?

  1. Deep-copies the data
  2. Moves the data
  3. Increments the reference count and returns another pointer to the same data
  4. Converts the Rc into an Arc

When are RefCell borrowing rules checked?

  1. At compile time
  2. At run time
  3. Never
  4. Only in release builds