FerrousPath

Level 2 · Practitioner· Lesson 5 of 8 · 30 min

Smart pointers and interior mutability

Box, Rc, RefCell, Weak and Cow — heap allocation, shared ownership, and mutation behind a shared reference.

A smart pointer is a type that owns some data and behaves like a pointer to it through the Deref trait. String and Vec are smart pointers. This lesson covers the ones you choose explicitly.

Box<T>: one owner, on the heap

#[derive(Debug)]
enum Expr {
    Num(f64),
    Add(Box<Expr>, Box<Expr>),
    Mul(Box<Expr>, Box<Expr>),
    Neg(Box<Expr>),
}

fn eval(e: &Expr) -> f64 {
    match e {
        Expr::Num(n) => *n,
        Expr::Add(a, b) => eval(a) + eval(b),
        Expr::Mul(a, b) => eval(a) * eval(b),
        Expr::Neg(a) => -eval(a),
    }
}

fn main() {
    // (2 + 3) * -4
    let e = Expr::Mul(
        Box::new(Expr::Add(Box::new(Expr::Num(2.0)), Box::new(Expr::Num(3.0)))),
        Box::new(Expr::Neg(Box::new(Expr::Num(4.0)))),
    );
    println!("{}", eval(&e));
}

Use Box for recursive types (which would otherwise have infinite size), for large values you want to move cheaply, and for trait objects (Box<dyn Trait>). A Box is exactly one pointer and frees its contents when dropped.

eval(a) works although a is a &Box<Expr>: deref coercion converts &Box<Expr> to &Expr automatically. The same mechanism turns &String into &str.

Rc<T>: shared ownership

Sometimes a value has no single obvious owner — a node referenced from several places in a graph, for example. Rc<T> (“reference counted”) keeps the value alive until the last Rc pointing at it is dropped.

use std::rc::Rc;

fn main() {
    let shared = Rc::new(String::from("shared config"));
    let a = Rc::clone(&shared); // bumps the count; does not copy the string
    let b = Rc::clone(&shared);
    println!("count = {}", Rc::strong_count(&shared));
    drop(a);
    println!("count = {}", Rc::strong_count(&shared));
    println!("{b}");
}

Rc<T> gives you only shared access to its contents — many owners, so no &mut. It is also single-threaded; the thread-safe version is Arc<T>, in Level 3.

RefCell<T>: interior mutability

The borrow rules are checked at compile time, and the check is conservative. RefCell<T> moves the same check to runtime: you can obtain a mutable borrow through a shared reference, and if you break the rule the program panics instead of failing to compile.

use std::cell::RefCell;

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

    cell.borrow_mut().push(4);          // mutable borrow, released at the semicolon
    println!("{:?}", cell.borrow());

    let reading = cell.borrow();
    let result = cell.try_borrow_mut(); // already borrowed: this fails
    println!("second borrow ok? {}", result.is_ok());
    drop(reading);
}

Cell<T> is the lighter relative for Copy types: get and set, no borrows, no panics.

Rc<RefCell<T>>: shared and mutable

Combining the two gives multiple owners that can all mutate — at the cost of runtime checks and the loss of compile-time guarantees.

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

#[derive(Debug)]
struct Account {
    balance: i64,
}

fn main() {
    let account = Rc::new(RefCell::new(Account { balance: 100 }));
    let cashier = Rc::clone(&account);
    let auditor = Rc::clone(&account);

    cashier.borrow_mut().balance -= 30;
    println!("auditor sees {}", auditor.borrow().balance);
}

Reach for this last, not first. Often an index into a Vec or a restructured ownership tree is simpler and faster.

Weak<T>: breaking cycles

Two Rcs pointing at each other never reach a count of zero and so never get freed. Weak<T> is a non-owning reference that must be upgraded before use:

use std::cell::RefCell;
use std::rc::{Rc, Weak};

struct Node {
    name: String,
    parent: RefCell<Weak<Node>>,
    children: RefCell<Vec<Rc<Node>>>,
}

fn main() {
    let root = Rc::new(Node {
        name: "root".into(),
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![]),
    });
    let leaf = Rc::new(Node {
        name: "leaf".into(),
        parent: RefCell::new(Rc::downgrade(&root)),
        children: RefCell::new(vec![]),
    });
    root.children.borrow_mut().push(Rc::clone(&leaf));

    let parent = leaf.parent.borrow().upgrade(); // Option<Rc<Node>>
    println!("{}'s parent: {:?}", leaf.name, parent.map(|p| p.name.clone()));
    println!("root: strong={} weak={}", Rc::strong_count(&root), Rc::weak_count(&root));
}

Parents own children (strong); children refer back to parents (weak).

Cow<T>: clone on write

Cow holds either a borrow or an owned value, and allocates only if it must change the data.

use std::borrow::Cow;

fn escape(input: &str) -> Cow<'_, str> {
    if input.contains('<') {
        Cow::Owned(input.replace('<', "&lt;"))
    } else {
        Cow::Borrowed(input) // common case: no allocation
    }
}

fn main() {
    for s in ["plain text", "a < b"] {
        let out = escape(s);
        let kind = if matches!(out, Cow::Borrowed(_)) { "borrowed" } else { "owned" };
        println!("{out} ({kind})");
    }
}

Choosing

Need Use
One owner, heap allocation Box<T>
Several owners, read-only, one thread Rc<T>
Several owners, mutation, one thread Rc<RefCell<T>>
Several owners across threads Arc<T>, Arc<Mutex<T>>
Reference that does not keep the value alive Weak<T>
Maybe borrowed, maybe owned Cow<'a, T>

Exercises

  1. Implement a singly linked stack: struct Stack<T> { head: Option<Box<Node<T>>> } with push, pop, and peek. Hint: self.head.take().
  2. Use Rc<RefCell<Vec<String>>> to build a logger shared by two structs that each append messages.
  3. Create a reference cycle on purpose with Rc<RefCell<Option<Rc<…>>>>, add a Drop implementation that prints, and confirm it never runs.
Solution to 1
struct Node<T> { value: T, next: Option<Box<Node<T>>> }
struct Stack<T> { head: Option<Box<Node<T>>> }

impl<T> Stack<T> {
    fn new() -> Self { Stack { head: None } }
    fn push(&mut self, value: T) {
        let next = self.head.take();
        self.head = Some(Box::new(Node { value, next }));
    }
    fn pop(&mut self) -> Option<T> {
        self.head.take().map(|node| {
            self.head = node.next;
            node.value
        })
    }
    fn peek(&self) -> Option<&T> {
        self.head.as_ref().map(|n| &n.value)
    }
}

fn main() {
    let mut s = Stack::new();
    s.push(1); s.push(2);
    println!("{:?}", s.peek());
    println!("{:?} {:?} {:?}", s.pop(), s.pop(), s.pop());
}

Option::take replaces the value with None and hands you the old one — the key trick for moving out of a &mut field.

Check your understanding

Pick an answer to see the explanation.

  1. 1.Why does enum List { Cons(i32, List), Nil } fail to compile?

  2. 2.What happens when you call borrow_mut() on a RefCell that is already borrowed?

  3. 3.How do you avoid a memory leak when two Rc values need to refer to each other?

Key terms in this lesson

Finished the lesson and the exercises?