Skip to chapter content
navan✳THE BUILD LABRUST / GUIDE
0/26 read
CHAPTER 16 / 21 · PROGRAMS AND TOOLS

Smart pointers and shared ownership.

Understand indirection, reference counts, interior mutability, and cleanup.

BY NAVAN SAMILONG READRUST 2024THEORY FIRST
01 / THE MENTAL MODEL

The idea behind the syntax.

A smart pointer owns or manages access to data while providing pointer-like behavior. Box<T> places a value behind an owned heap allocation and gives recursive types a known-size handle. Rc<T> lets several owners in one thread share a value through reference counting. RefCell<T> moves borrow checking for a particular value to runtime, allowing mutation through an otherwise shared owner under strict dynamic rules.

These types are precise tools, not escape hatches from ownership. A Box still has one owner. An Rc clone increments a count rather than copying the underlying value, and its shared ownership does not itself permit mutation. RefCell can panic if code violates its borrowing rules at runtime. Combining Rc<RefCell<T>> is useful in some local graph-like structures, but it increases the burden of reasoning about who can mutate what.

02 / THE RULES

What Rust is checking.

Drop runs when an owned value leaves scope, including fields owned by a struct. Rc releases its inner value when the last strong owner is dropped. Cycles of strong Rc references never reach a count of zero, so Weak references model back-links or observers that do not own the target. Upgrading a Weak reference returns an Option because the target may already be gone.

Deref lets pointer-like types expose access to their inner values, while Drop customises cleanup when a value leaves scope. Neither makes arbitrary aliasing safe. Read the examples by drawing a graph of ownership: arrows from owners to allocations, strong versus weak links, and the points where counts change. This graph explains both the convenience of sharing and the danger of cycles.

03 / CODE, EXPLAINED

See the rule in context.

Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.

EXAMPLE 01

Box & recursive data

Box<T> owns a heap-allocated T and provides a fixed-size owning pointer. Recursive types need indirection because a value cannot contain an infinitely large copy of itself. An enum can therefore place its next node behind Box. A boxed allocation is not automatically faster than a value stored directly; it adds indirection and allocation work. Use Vec for ordinary contiguous lists unless a different structure serves the operation you need. Box is also useful for owning trait objects.

box.rs
enum List {
    Node(i32, Box<List>),
    End,
}
fn sum(list: &List) -> i32 {
    match list {
        List::Node(value, next) => value + sum(next),
        List::End => 0,
    }
}
fn main() {
    let list = List::Node(3, Box::new(List::Node(4, Box::new(List::End))));
    println!("sum={}", sum(&list));
}
OUTPUT
sum=7
  1. Box breaks the infinitely recursive layout.
  2. The recursive function borrows each node.
  3. Dropping the owner cleans up its owned boxes.

The boundary: Very deep recursive traversal and recursive drop can overflow the stack. A linked shape does not guarantee bounded stack usage.

EXAMPLE 02

Rc, RefCell & interior mutability

Rc<T> provides reference-counted shared ownership within one thread. RefCell<T> allows interior mutation by checking borrowing rules at runtime: many shared borrows or one exclusive borrow. Violations panic with borrow or can return an error with try_borrow. Rc does not make data thread-safe, and reference cycles can prevent cleanup; Weak references help represent non-owning back-links. Prefer simple ownership first, then introduce these tools when the graph of owners genuinely requires them.

rc-refcell.rs
use std::{cell::RefCell, rc::Rc};
fn main() {
    let shared = Rc::new(RefCell::new(vec!["plan"]));
    let other = Rc::clone(&shared);
    other.borrow_mut().push("build");
    println!("{:?}", shared.borrow());
    println!("owners={}", Rc::strong_count(&shared));
}
OUTPUT
["plan", "build"]
owners=2
  1. Rc::clone shares the allocation rather than copying the vector.
  2. The temporary mutable borrow ends after push.
  3. The later shared borrow sees the update.

The boundary: RefCell moves borrowing enforcement to runtime; it does not remove the rules. Keep RefMut guards short.

EXAMPLE 03

Drop, RAII & Weak

RAII ties resource cleanup to ownership: file handles, locks, and heap allocations are released as their owners are dropped. The Drop trait customizes cleanup, but you should keep it dependable and avoid panicking. std::mem::drop ends ownership early. Weak<T> points at a reference-counted allocation without keeping its value alive; upgrade returns Option because the value may already be gone. Weak is useful for parent links and registries where observation should not imply ownership.

drop-weak.rs
use std::rc::Rc;
fn main() {
    let owner = Rc::new(String::from("session"));
    let observer = Rc::downgrade(&owner);
    println!("alive={}", observer.upgrade().is_some());
    drop(owner);
    println!("alive={}", observer.upgrade().is_some());
}
OUTPUT
alive=true
alive=false
  1. downgrade creates a non-owning weak handle.
  2. The first upgrade temporarily creates a strong owner.
  3. After the final strong owner drops, upgrade returns None.

The boundary: A cycle of strong Rc or Arc pointers can leak its values. Reference counting cannot discover that the cycle is unreachable.

04 / THE CONNECTION

Keep this model.

Smart pointers change where data lives or how many owners it has. Their types preserve explicit rules for access, mutation, and cleanup.

Finished reading?
Built with curiosity. By Navan Sami. ↗Rust · The rules behind the code.