CourseLesson 13 · Smart PointersSolve

Lesson 13

Smart Pointers

Every reference you have written so far borrows a value that some variable still owns. This lesson covers three types that change what a pointer can do: own a value instead of borrowing it, be owned by more than one variable at once, and allow a change through a reference that is supposed to be read-only.

Box<T>: One Value on the Heap

Box<T> is the simplest of the three. It puts one value of type T on the heap, and holds a pointer to it on the stack. Unlike a plain reference, a Box owns the value: when the Box is dropped, the value is dropped too.

fn main() {
    let number = Box::new(5);
    println!("{number}");
}
5

There is little reason to box a plain number. Box earns its place when a value’s size cannot be known while the program is compiled, which happens whenever a type contains a value of its own type.

enum List {
    Cons(i32, List),
    Nil,
}

fn main() {
    let list = List::Cons(1, List::Cons(2, List::Nil));
}
error[E0072]: recursive type `List` has infinite size
 --> src/main.rs:1:1
  |
1 | enum List {
  | ^^^^^^^^^
2 |     Cons(i32, List),
  |               ---- recursive without indirection
  |
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to
      break the cycle
  |
2 |     Cons(i32, Box<List>),
  |               ++++    +

List is a linked list: each Cons holds one number and the rest of the list. To work out the size of List, the compiler would have to work out the size of the List inside it, which itself holds a List, and so on forever. There is no finite answer, so the compiler refuses.

Box<List> fixes this. A Box is always one pointer wide, no matter what it points at, so Cons(i32, Box<List>) has a fixed size: one i32 plus one pointer. The rest of the list still exists, but it lives on the heap, one Box away instead of packed directly inside.

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

use List::{Cons, Nil};

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

    let mut current = &list;
    loop {
        match current {
            Cons(value, next) => {
                println!("{value}");
                current = next;
            }
            Nil => break,
        }
    }
}
1
2
3

Box::new(Nil) puts the empty tail on the heap. Each Box::new(Cons( ...)) does the same for the list built on top of it. The loop follows the pointer from one Cons to the next, stopping at Nil. Outside of this kind of self-referencing type, you will rarely reach for Box directly: the trait objects from an earlier lesson, written Box<dyn Trait>, are the other common place it appears.

Key idea

A Box costs one heap allocation and one pointer indirection. Use it only when a value’s size cannot be known at compile time, such as a type holding itself, or when a value has to be a fixed, known size for some other reason, such as a trait object.

Rc<T>: More Than One Owner

The ownership rules from earlier say a value has exactly one owner. That rule is right most of the time, but occasionally two parts of a program legitimately need to share one piece of data, and neither one is clearly responsible for dropping it. Rc<T>, short for reference counted, allows this. It keeps a count of how many owners a value has, and only drops the value once that count reaches zero.

use std::rc::Rc;

fn main() {
    let title = Rc::new(String::from("Rust in Practice"));
    println!("count after creating title: {}", Rc::strong_count(&title));

    let copy_for_shelf = Rc::clone(&title);
    println!("count after cloning once: {}", Rc::strong_count(&title));

    {
        let copy_for_search = Rc::clone(&title);
        println!("count after cloning twice: {}", Rc::strong_count(&title));
        println!("{copy_for_search}");
    }

    println!("count after inner scope ends: {}", Rc::strong_count(&title));
    println!("{copy_for_shelf}");
}
count after creating title: 1
count after cloning once: 2
count after cloning twice: 3
Rust in Practice
count after inner scope ends: 2
Rust in Practice
  • Rc::new puts the String on the heap and starts its count at 1.

  • Rc::clone(&title) does not copy the text. It copies the pointer and adds one to the count. This is why it is cheap to call as often as needed, unlike the .clone() you have used on String, which does copy the data.

  • Rc::strong_count reads the current count. It exists mainly to show what is happening here; a real program rarely needs to read it.

  • When copy_for_search goes out of scope at the closing brace, the count drops back to 2. The text itself is not dropped, because two owners, title and copy_for_shelf, are still holding it.

  • The text is only dropped once the count reaches 0, which happens at the end of main here.

Key idea

Rc<T> only allows reading the value it owns, through &T, the same as an ordinary shared reference. Two owners are still not allowed to change the value at the same time, for the same reason two & references were not allowed to coexist with a &mut one. Rc shares ownership. It does not by itself allow mutation.

Interior Mutability and RefCell<T>

Every borrowing rule you have used so far is checked while the program is compiled: the compiler reads the code and refuses to build it if two &mut references could exist at once. Interior mutability is a pattern where a value looks read-only from the outside, through an ordinary & reference, but can still be changed on the inside. RefCell<T> is the type that provides it. It moves the borrowing check from compile time to run time.

use std::cell::RefCell;

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

    *count.borrow_mut() += 1;
    *count.borrow_mut() += 1;

    println!("count is {}", count.borrow());
}
count is 2
  • count is not declared mut, and RefCell::new does not return a &mut reference. Yet count.borrow_mut() is allowed to change the value inside.

  • borrow_mut returns a value that lets you write through it with *, similar to a &mut reference. borrow does the same for reading.

  • The two calls to borrow_mut do not overlap: each one is used on its own line and then dropped before the next line runs. The rules of borrowing still apply. RefCell only checks them while the program runs instead of while it compiles.

Break the rule, and the program compiles, but crashes when it runs.

use std::cell::RefCell;

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

    let first = count.borrow_mut();
    let second = count.borrow_mut();

    println!("{first} {second}");
}
thread 'main' (65547) panicked at src/main.rs:7:24:
RefCell already borrowed

first and second are two &mut-like borrows of the same value, alive at the same time. The compiler cannot see this, because RefCell hides the check inside its own methods. borrow_mut checks at the moment it is called, finds an earlier borrow still alive, and panics instead of letting the second one through.

Key idea

A normal &mut reference is checked once, before the program runs, and costs nothing while it runs. A RefCell moves the same check to every call of borrow or borrow_mut, which costs a little time on every call, and can panic instead of failing to compile. Reach for it only when the compile-time rules are too strict for a pattern you genuinely need, most often alongside Rc.

Rc<RefCell<T>>: Shared and Mutable

Rc<T> allows more than one owner but only reading. RefCell<T> allows writing but has one owner. Putting a RefCell inside an Rc gives both at once: several owners, any of which can change the shared value.

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

struct Account {
    balance: RefCell<i32>,
}

fn deposit(account: &Rc<Account>, amount: i32) {
    *account.balance.borrow_mut() += amount;
}

fn main() {
    let account = Rc::new(Account { balance: RefCell::new(0) });
    let branch_a = Rc::clone(&account);
    let branch_b = Rc::clone(&account);

    deposit(&branch_a, 50);
    deposit(&branch_b, 30);

    println!("balance: {}", account.balance.borrow());
}
balance: 80

branch_a and branch_b are two separate owners of the same Account, made with Rc::clone. Both call deposit, and both changes land on the one balance that all three variables point at, because RefCell lets deposit write to it through a shared &Rc<Account>. Without RefCell, balance would need &mut to change, and Rc never hands out &mut.

A Bridge to Threads: Arc<T> and Mutex<T>

A thread is a separate line of a program running at the same time as the rest of it. Rc<T> and RefCell<T> were not built with threads in mind, and Rust will not let you send either of them to one.

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

fn main() {
    let n = Rc::new(RefCell::new(0));
    let h = thread::spawn(move || *n.borrow_mut() += 1);
    h.join().unwrap();
}
error[E0277]: `Rc<RefCell<i32>>` cannot be sent between
              threads safely
   --> src/main.rs:7:27
    |
  7 |     let h = thread::spawn(move || *n.borrow_mut() += 1);
    |             ------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |             |
    |             required by a bound introduced by this call
    |
    = help: the trait `Send` is not implemented for
      `Rc<RefCell<i32>>`
  • thread::spawn starts a new thread and runs the closure passed to it on that thread, while main keeps running too.

  • move makes the closure take ownership of the variables it uses from the surrounding code, here n, instead of borrowing them. A borrow could outlive the variable it points at once two threads are involved, so a thread closure has to own what it uses.

  • h.join() blocks until that thread finishes. .unwrap() is needed because join returns a Result, the same as the error handling seen in an earlier lesson.

  • Rc’s count is a plain number, changed with no protection against two threads changing it at the same instant. If that were allowed, two threads could both read the count, both add one, and both write back the same wrong total, losing an owner. Rust refuses to compile this program rather than risk it.

Arc<T>, short for atomic reference counted, is the thread-safe version of Rc<T>. It works the same way, but its count is changed with an operation that cannot be interrupted partway through by another thread. Mutex<T>, short for mutual exclusion, is the thread-safe version of RefCell<T>: it also moves the borrow check to run time, but only one thread at a time is allowed to hold the unlocked value, and every other thread waits its turn.

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

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

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

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

    println!("balance: {}", account.lock().unwrap());
}
balance: 50
  • Arc::new and Arc::clone work exactly like Rc::new and Rc::clone. Each of the five threads gets its own clone, pointing at the same Mutex.

  • account.lock() waits until no other thread is holding the value, then hands it back, wrapped the same Result way as join. Once balance goes out of scope at the end of the closure, the lock is released for the next thread waiting on it.

  • Every deposit is still forced to happen one at a time, even though five threads start at nearly the same moment. That is what keeps the final total correct.

Key idea

Reach for Rc<RefCell<T>> to share and mutate a value between different parts of a single-threaded program. Reach for Arc<Mutex<T>> for the same pattern once more than one thread is involved. Using Rc or RefCell across threads is not merely discouraged, it is refused by the compiler outright, which is why a mistaken choice is caught before the program ever runs.

Common Mistakes

Reaching for Rc<RefCell<T>> as a Default

Rc<RefCell<T>> solves a real problem, but it gives up the compile-time checking that makes Rust’s ownership rules useful in the first place. A RefCell panic happens only when that exact line runs, which can be far later than the mistake that caused it. Reach for it once you have a genuine need for shared, mutable data. Do not reach for it merely to avoid working out who owns a value.

Forgetting That borrow_mut Panics Instead of Refusing

use std::cell::RefCell;

fn main() {
    let numbers = RefCell::new(vec![1, 2, 3]);

    let first = numbers.borrow();
    numbers.borrow_mut().push(4);

    println!("{first:?}");
}

This compiles without a single warning, because RefCell has no way to warn you at compile time. It panics the moment borrow_mut runs, with first still alive. Read every RefCell the same way you read ordinary borrows: two borrows that read are fine together, one that writes must be alone.

Cloning an Rc When a Real Clone Was Needed

use std::rc::Rc;

fn main() {
    let numbers = Rc::new(vec![1, 2, 3]);
    let copy = Rc::clone(&numbers);

    copy.push(4);
}
error[E0596]: cannot borrow data in an `Rc` as mutable
 --> src/main.rs:7:5
  |
7 |     copy.push(4);
  |     ^^^^ cannot borrow as mutable
  |
  = help: trait `DerefMut` is required to modify through a
    dereference, but it is not implemented for `Rc<Vec<i32>>`

Rc::clone makes copy a second owner of the same vector, not a second, independent vector. Rc never hands out &mut access, so push does not compile. If an independent copy really is needed, clone the value inside instead: (*numbers).clone(). If shared mutation is needed, wrap the value in a RefCell before putting it in the Rc.

Using Arc<Mutex<T>> Where a Single Thread Would Do

Arc and Mutex cost more than Rc and RefCell: the count is updated with a slower, interruption-safe operation, and every lock can make a thread wait. A program with no threads never needs either. Reach for Arc<Mutex<T>> only once a value genuinely has to cross from one thread into another.

Reference

Written asWhat it does
Box<T>One value, owned, on the heap.
Box::new(v)Puts v on the heap and returns a Box to it.
Rc<T>A value that can have more than one owner.
Rc::clone(&r)A cheap new owner, count up by one.
Rc::strong_count(&r)How many owners r currently has.
RefCell<T>Borrowing rules checked while the program runs.
r.borrow()A read-only borrow, checked at run time.
r.borrow_mut()A writable borrow, checked at run time. Panics if another borrow is alive.
Rc<RefCell<T>>Shared ownership, with mutation through any owner.
Arc<T>Rc, safe to share between threads.
Mutex<T>RefCell, safe to share between threads.
m.lock()Waits, then returns exclusive access to m’s value.
thread::spawn(f)Runs f on a new thread.
handle.join()Waits for that thread to finish.

Check what stuck

The practice sheet for this lesson has 50 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.

Start practice →