Skip to content
RustLearn

Module 15 — Smart Pointers & Interior Mutability

Goal

Box, Rc, RefCell, Deref and Drop — how to build trees, graphs and shared state when a single owner is not enough.

Start here — what this module is really about

Everything so far assumed one owner per value. This module is about the cases where that is genuinely not enough, and the tools Rust provides instead — without giving up safety.

A smart pointer is a value that behaves like a reference but owns what it points at and does something extra. You have already used two: String and Vec<T> are both smart pointers, owning heap data and cleaning it up automatically.

The four that matter here, and the exact problem each solves:

  • Box<T> — one owner, data on the heap. Use it when a type must have a known size but the data is large or recursive. A linked list node containing another node would be infinitely large; a node containing a Box to another node is one pointer wide.
  • Rc<T> — several owners, single-threaded. Reference counting: each clone increments a counter, each drop decrements it, and the value is cleaned up when it reaches zero. Use it when several parts of a program genuinely need to keep the same data alive and there is no single obvious owner.
  • RefCell<T> — borrow checking moved to runtime. The borrowing rules still apply, but they are enforced while the program runs instead of while it compiles, and breaking them panics rather than failing to build. Use it when you know an access pattern is safe but cannot express it statically.
  • Weak<T> — a reference that does not keep things alive. The fix for two Rcs pointing at each other and neither ever reaching zero.

One honest warning before you start: Rc<RefCell<T>> is a legitimate tool and also a common way to write Rust as though it were a garbage-collected language. Reach for it when you have a real reason, not to escape a borrow error — the borrow error is usually pointing at a design that wants restructuring.

The one sentence to remember: Box for one owner on the heap, Rc for shared ownership, RefCell to defer borrow checking to runtime — and use them when the design needs them, not to silence the compiler.

Learning objectives

  • Use Box<T> for heap allocation, recursive types, and trait objects
  • Use Rc<T> for shared ownership and understand reference counting
  • Use RefCell<T> for interior mutability and runtime borrow checking
  • Combine Rc<RefCell<T>> to build graphs and observers
  • Avoid reference cycles with Weak<T>
  • Implement Deref and Drop

15.1 What a smart pointer is

A smart pointer is a struct that behaves like a pointer but owns data and adds behaviour. The pattern is: implement Deref (so * and method calls work through it) and usually Drop (so cleanup happens automatically). String and Vec<T> are smart pointers you've been using all along.

TypeOwnershipMutabilityThread-safeCost
Box<T>singleinheritedyes (if T is)one allocation
Rc<T>sharedimmutable❌ nonon-atomic refcount
Arc<T>sharedimmutable✅ yesatomic refcount
RefCell<T>singleinterior, runtime-checked❌ noruntime borrow flags
Mutex<T>singleinterior, blocking✅ yeslock
Cell<T>singleinterior, copy in/out❌ nofree

15.2 Box<T> — the simplest smart pointer

rust
let b = Box::new(5);          // the 5 lives on the heap
println!("{b}");              // auto-deref

Three real uses:

1. Recursive types

rust
// ❌ infinite size: List contains List contains List...
// enum List { Cons(i32, List), Nil }

// ✅ Box has a known size (one pointer)
#[derive(Debug)]
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))))));
    println!("{list:?}");
}

The compiler must know a type's size at compile time. Box<List> is one pointer, regardless of how deep the list goes, so the recursion terminates.

2. Trait objects

rust
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Square(2.0))];
fn make() -> Box<dyn Fn(i32) -> i32> { Box::new(|x| x + 1) }

3. Moving large data without copying

rust
let huge = Box::new([0u8; 1_000_000]);
let moved = huge;               // moves one pointer, not a megabyte

Analogy — the address card

Box<T> is a card on your desk with a warehouse address on it. The card is small and a fixed size, which is why it can sit inside a struct whose size must be known — even when the thing at the address is enormous, or is another card pointing at another one (which is how a recursive type stops being infinitely large).

15.3 Rc<T> — shared ownership

Sometimes one value genuinely has multiple owners — a node in a graph, a config shared by several subsystems. Rc keeps a count and drops the value when the count hits zero.

rust
use std::rc::Rc;

fn main() {
    let a = Rc::new(String::from("shared"));
    println!("count = {}", Rc::strong_count(&a));   // 1

    let b = Rc::clone(&a);                          // count 2 — NOT a deep copy
    {
        let c = Rc::clone(&a);
        println!("count = {}", Rc::strong_count(&a));   // 3
    }                                               // c dropped
    println!("count = {}", Rc::strong_count(&a));   // 2
    println!("{a} {b}");
}

Notes:

  • Rc::clone(&a) is conventional over a.clone() — it makes the cheap refcount bump visually distinct from an expensive deep clone.
  • Rc<T> gives you &T only. You cannot mutate through an Rc (unless the inner type provides interior mutability).
  • Rc is single-threaded. The multithreaded version is Arc (module 17), which uses atomic operations and is slightly slower.
rust
// two lists sharing a tail
use std::rc::Rc;
enum List { Cons(i32, Rc<List>), Nil }
use List::{Cons, Nil};

let shared = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
let a = Cons(3, Rc::clone(&shared));
let b = Cons(4, Rc::clone(&shared));

How Rc actually shares

rust
use std::rc::Rc;

let a = Rc::new(String::from("shared"));
println!("{}", Rc::strong_count(&a));    // 1

let b = Rc::clone(&a);                   // NOT a deep copy
println!("{}", Rc::strong_count(&a));    // 2

{
    let c = Rc::clone(&a);
    println!("{}", Rc::strong_count(&a)); // 3
}                                         // c dropped
println!("{}", Rc::strong_count(&a));    // 2

What is physically happening: the String sits on the heap once, next to a counter. Rc::clone copies only a pointer and adds one to that counter — it is cheap, and the convention of writing Rc::clone(&a) rather than a.clone() exists precisely to make that visible at a glance. When each Rc is dropped the counter falls, and at zero the String is freed.

Two limits to know now:

  • Rc gives you shared reading, not shared writing. You cannot get a &mut out of an Rc, because several owners plus mutation is exactly what the borrowing rules forbid. Combining it with RefCell is how you get shared mutation — see §15.5.
  • Rc is single-threaded. Its counter is not safe against concurrent updates, and the compiler will refuse to send one across threads. The multi-threaded version is Arc, in module 17.

Analogy — the shared flat

Ownership so far has been one tenant per flat. Rc is a shared tenancy with a counter by the door: every new tenant increments it, everyone who leaves decrements it, and whoever turns the last one off cleans up. Nobody has to know who else is living there, and nothing is thrown away while a single tenant remains.

15.4 RefCell<T> — interior mutability

RefCell moves borrow checking from compile time to runtime. You can mutate through an immutable reference; if you violate the borrowing rules, the program panics instead of failing to compile.

rust
use std::cell::RefCell;

fn main() {
    let c = RefCell::new(5);

    *c.borrow_mut() += 10;              // mutable borrow
    println!("{}", c.borrow());         // immutable borrow -> 15

    // ❌ panics at runtime: already borrowed
    // let b1 = c.borrow_mut();
    // let b2 = c.borrow_mut();
}

API:

rust
c.borrow()        // Ref<T>       — panics if mutably borrowed
c.borrow_mut()    // RefMut<T>    — panics if borrowed at all
c.try_borrow()    // Result       — non-panicking
c.replace(v)      // swap, return old
c.into_inner()    // consume, return T

The borrow guard (Ref/RefMut) releases when dropped, so scope your borrows tightly:

rust
{
    let mut m = c.borrow_mut();
    *m += 1;
}                                  // released here
println!("{}", c.borrow());        // ✅ no panic

When is this legitimate?

The canonical case is a mock object in a test — an interface takes &self but the mock needs to record calls:

rust
trait Messenger {
    fn send(&self, msg: &str);      // &self, not &mut self
}

struct MockMessenger { sent: RefCell<Vec<String>> }

impl Messenger for MockMessenger {
    fn send(&self, msg: &str) {
        self.sent.borrow_mut().push(msg.to_string());   // mutate through &self
    }
}

Also: memoization caches, graph structures, and observer patterns.

Cost

RefCell trades compile-time guarantees for runtime checks and a possible panic. Use it when you're confident the borrows are actually disjoint but the compiler can't prove it — not as a way to avoid learning ownership.

Cell<T> is the cheaper cousin for Copy types: get()/set() with no borrow tracking at all.


RefCell — the same rules, checked later

RefCell does not remove the borrowing rules. It moves when they are checked:

rust
use std::cell::RefCell;

let c = RefCell::new(5);

{
    let mut m = c.borrow_mut();   // runtime check: is anything else borrowing?
    *m += 1;
}                                 // the borrow ends here, when `m` is dropped

println!("{}", c.borrow());       // 6

And what happens when you break the rule:

rust
let first = c.borrow_mut();
let second = c.borrow_mut();      // 💥 panics: already mutably borrowed

That is a runtime panic, not a compile error. You have traded a guarantee for flexibility, and the cost of getting it wrong is now a crash in production rather than a red build. That trade is worth making rarely and deliberately.

The two rules that keep it manageable:

  1. Keep borrows short. The borrow lasts until the guard value is dropped, so a let binding holds it much longer than an inline c.borrow_mut() inside one expression. Most already borrowed panics are a guard living longer than the author realised.
  2. Prefer the compile-time version when you can express it. RefCell is for the cases you genuinely cannot — a cache inside an otherwise immutable object, a graph node that must point back at its parent, mock objects in tests recording calls.

Analogy — the borrow rules, enforced at the desk

RefCell does not abolish the borrowing rules; it moves the guard from the door to the desk. Instead of the compiler refusing at build time, a librarian checks the ledger when you actually ask — and if someone already has the editing copy, you are turned away right then, at runtime, with a panic. Same rules, later check, and you take responsibility for that trade.

15.5 Rc<RefCell<T>> — shared mutable state

Combining them gives multiple owners and mutability:

rust
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 teller_a = Rc::clone(&account);
    let teller_b = Rc::clone(&account);

    teller_a.borrow_mut().balance += 50;
    teller_b.borrow_mut().balance -= 30;

    println!("{:?}", account.borrow());          // Account { balance: 120 }
    println!("owners: {}", Rc::strong_count(&account));   // 3
}

A shared, mutable tree:

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

#[derive(Debug)]
struct Node {
    value: i32,
    children: RefCell<Vec<Rc<Node>>>,
}

fn main() {
    let leaf = Rc::new(Node { value: 3, children: RefCell::new(vec![]) });
    let branch = Rc::new(Node { value: 5, children: RefCell::new(vec![Rc::clone(&leaf)]) });
    branch.children.borrow_mut().push(Rc::new(Node { value: 7, children: RefCell::new(vec![]) }));
    println!("{branch:?}");
}

TS ↔ Rust: Rc<RefCell<T>> is roughly what every JavaScript object reference is by default. Rust makes you spell it out, so the cost and the aliasing are visible.

15.6 Weak<T> and reference cycles

Rc cannot detect cycles — a cycle keeps the count above zero forever and leaks:

rust
// parent -> child (strong) and child -> parent (strong) = leak

Weak<T> is a non-owning reference. It doesn't increment the strong count and doesn't keep the value alive; upgrade() returns Option<Rc<T>>, None if the value is gone.

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

#[derive(Debug)]
struct Node {
    value: i32,
    parent: RefCell<Weak<Node>>,        // weak upward
    children: RefCell<Vec<Rc<Node>>>,   // strong downward
}

fn main() {
    let leaf = Rc::new(Node {
        value: 3,
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![]),
    });

    let branch = Rc::new(Node {
        value: 5,
        parent: RefCell::new(Weak::new()),
        children: RefCell::new(vec![Rc::clone(&leaf)]),
    });

    *leaf.parent.borrow_mut() = Rc::downgrade(&branch);

    println!("leaf parent value = {:?}",
             leaf.parent.borrow().upgrade().map(|p| p.value));    // Some(5)
    println!("branch strong = {}, weak = {}",
             Rc::strong_count(&branch), Rc::weak_count(&branch)); // 1, 1
}

The rule

Ownership goes one direction (strong), back-references go the other (weak). Parent owns child; child weakly points at parent.


Analogy — the reference cycle that keeps the lights on

Two Rcs pointing at each other are two tenants each waiting for the other to leave — the counter never reaches zero and the flat is never cleaned. Weak is a tenant who is registered as a visitor rather than a leaseholder: they can still find the flat, but they do not keep it standing. Parent-to-child strong, child-to-parent weak, and the cycle is broken.

15.7 Deref and Drop

rust
use std::ops::Deref;

struct MyBox<T>(T);

impl<T> MyBox<T> {
    fn new(x: T) -> MyBox<T> { MyBox(x) }
}

impl<T> Deref for MyBox<T> {
    type Target = T;
    fn deref(&self) -> &T { &self.0 }
}

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

fn main() {
    let b = MyBox::new(5);
    assert_eq!(5, *b);                     // *b becomes *(b.deref())

    let m = MyBox::new(String::from("Rust"));
    hello(&m);                             // deref coercion: &MyBox<String> -> &String -> &str
}

Deref coercion is why &String works where &str is expected, and why &Vec<T> works where &[T] is expected. It applies automatically at function call sites and chains as many times as needed.

Drop (from module 04) completes the picture — implement both and your type behaves like a built-in pointer:

rust
impl<T> Drop for MyBox<T> {
    fn drop(&mut self) { println!("dropping MyBox"); }
}

Jargon buster

Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.

TermIn plain English
smart pointerA value that points at data, owns it, and adds behaviour — String, Vec, Box, Rc.
Box<T>Single ownership of a value on the heap.
recursive typeA type containing itself — needs a Box to have a finite size.
Rc<T>Reference-counted shared ownership, single-threaded.
strong countHow many Rcs currently keep a value alive.
RefCell<T>Borrow rules enforced at runtime instead of compile time.
interior mutabilityChanging data through a shared reference, safely, via a type like RefCell.
guardThe value returned by borrow()/borrow_mut(); the borrow lasts until it is dropped.
Weak<T>A non-owning reference that does not keep data alive; upgrade it to use it.
reference cycleTwo values keeping each other alive forever. The one way to leak memory in safe Rust.
DerefThe trait that lets a smart pointer be used like a plain reference.
deref coercionThe compiler automatically turning &String into &str, &Box<T> into &T.

If you get stuck

The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.

What you seeWhat it meansWhat to do
error[E0072]: recursive type has infinite sizeA struct contains itself directly.Box the recursive field: Box<Node>. The help: line says exactly this.
already borrowed: BorrowMutError (at runtime)Two RefCell borrows overlapped.Shorten the first borrow — usually a guard held in a let that should have been inline.
error[E0596]: cannot borrow as mutable on an RcRc alone gives shared read access only.Rc<RefCell<T>> if you truly need shared mutation.
Rc<T> cannot be sent between threads safelyYou used Rc across threads.Use Arc (module 17).
Memory usage grows and nothing is freedProbably a reference cycle.Make one direction Weak — typically parent-to-child strong, child-to-parent weak.

Now make it stick: work through the drills for this module, then carry on to Module 16 — Testing, Docs & Tooling.