Module 15 Exercises — Smart Pointers & Interior Mutability
How to use this page
Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.
Before you start, be able to say which of Box, Rc, RefCell you would reach for, and why, for:
- a binary tree node with two children;
- a value several parts of a program must keep alive;
- a struct that must update an internal cache from a
&selfmethod.
If a drill tempts you into Rc<RefCell<T>> for something a plain &mut could do, stop and try the plain version first. Knowing when not to reach for these is as much the point as knowing how they work.
Part A — Warm-Up Drills
Short reps on the mechanics. Do them until the syntax stops costing you any thought.
🟢 Exercise 15.1 — Cons list
Build the recursive List enum with Box, construct 1 -> 2 -> 3 -> Nil, and write
fn sum(list: &List) -> i32 recursively.
Solution
#[derive(Debug)]
enum List { Cons(i32, Box<List>), Nil }
use List::{Cons, Nil};
fn sum(list: &List) -> i32 {
match list {
Cons(v, rest) => v + sum(rest),
Nil => 0,
}
}
fn main() {
let l = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
assert_eq!(sum(&l), 6);
println!("{l:?}");
}🟢 Exercise 15.2 — Reference counting trace
Predict the printed counts:
use std::rc::Rc;
let a = Rc::new(1);
println!("{}", Rc::strong_count(&a));
let b = Rc::clone(&a);
println!("{}", Rc::strong_count(&a));
{
let c = Rc::clone(&b);
println!("{}", Rc::strong_count(&a));
}
drop(b);
println!("{}", Rc::strong_count(&a));Answer
1, 2, 3, 1.
Part B — Core Exercises
The real practice. Attempt each one fully — compiler errors included — before opening a solution.
🟡 Exercise 15.3 — Shared counter
Build Rc<RefCell<i32>> shared by three "workers" (closures), each incrementing it a
different number of times. Print the final value and the strong count.
Solution
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let counter = Rc::new(RefCell::new(0));
let workers: Vec<Box<dyn Fn()>> = vec![1, 2, 3]
.into_iter()
.map(|n| {
let c = Rc::clone(&counter);
Box::new(move || { *c.borrow_mut() += n; }) as Box<dyn Fn()>
})
.collect();
for w in &workers { w(); w(); }
println!("value = {}", counter.borrow()); // 12
println!("owners = {}", Rc::strong_count(&counter)); // 4
}🟡 Exercise 15.4 — Trigger a RefCell panic
Write code that panics with already borrowed: BorrowMutError, then fix it two ways:
by scoping the borrow, and by using try_borrow_mut.
Solution
use std::cell::RefCell;
fn main() {
let c = RefCell::new(vec![1, 2, 3]);
// panics:
// let r = c.borrow();
// let mut m = c.borrow_mut();
// fix 1: scope it
let len = { c.borrow().len() };
c.borrow_mut().push(len as i32);
// fix 2: handle it
let guard = c.borrow();
match c.try_borrow_mut() {
Ok(_) => println!("got mutable access"),
Err(e) => println!("could not borrow mutably: {e}"),
}
drop(guard);
println!("{:?}", c.borrow());
}Part C — Challenges
Longer builds. Expect to fight the borrow checker here; that fight is the lesson.
🔴 Exercise 15.5 — Observer pattern
Implement a Subject holding Vec<Weak<RefCell<Observer>>> and notifying all live
observers of an event. Dropping an observer should remove it from notification without
leaking. Verify the strong count never grows and that dropped observers are pruned.
Solution
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct Observer { name: String, received: Vec<String> }
impl Observer {
fn new(name: &str) -> Rc<RefCell<Observer>> {
Rc::new(RefCell::new(Observer { name: name.into(), received: vec![] }))
}
}
#[derive(Default)]
struct Subject { observers: Vec<Weak<RefCell<Observer>>> }
impl Subject {
fn subscribe(&mut self, o: &Rc<RefCell<Observer>>) {
self.observers.push(Rc::downgrade(o));
}
fn notify(&mut self, event: &str) {
// prune dead observers while notifying live ones
self.observers.retain(|w| match w.upgrade() {
Some(o) => {
o.borrow_mut().received.push(event.to_string());
true
}
None => false,
});
}
}
fn main() {
let mut subject = Subject::default();
let a = Observer::new("a");
subject.subscribe(&a);
{
let b = Observer::new("b");
subject.subscribe(&b);
subject.notify("event1");
assert_eq!(b.borrow().received.len(), 1);
assert_eq!(Rc::strong_count(&b), 1); // subject holds only a Weak
} // b dropped
subject.notify("event2");
assert_eq!(subject.observers.len(), 1); // b was pruned
println!("{:?}", a.borrow().received); // ["event1", "event2"]
}Rc::strong_count(&b) == 1 is the assertion that matters: the subject does not keep
observers alive, so there is no leak and no cycle.
🔴 Exercise 15.6 — Doubly linked list
Implement a doubly linked list of i32 where each node has next: Option<Rc<RefCell<Node>>>
and prev: Option<Weak<RefCell<Node>>>. Support push_back, push_front, and
to_vec_forward / to_vec_backward. Explain why prev must be Weak.
Solution
use std::cell::RefCell;
use std::rc::{Rc, Weak};
type Link = Option<Rc<RefCell<Node>>>;
struct Node { value: i32, next: Link, prev: Option<Weak<RefCell<Node>>> }
#[derive(Default)]
struct List { head: Link, tail: Link }
impl List {
fn push_back(&mut self, value: i32) {
let node = Rc::new(RefCell::new(Node { value, next: None, prev: None }));
match self.tail.take() {
Some(old) => {
node.borrow_mut().prev = Some(Rc::downgrade(&old));
old.borrow_mut().next = Some(Rc::clone(&node));
self.tail = Some(node);
}
None => {
self.head = Some(Rc::clone(&node));
self.tail = Some(node);
}
}
}
fn push_front(&mut self, value: i32) {
let node = Rc::new(RefCell::new(Node { value, next: None, prev: None }));
match self.head.take() {
Some(old) => {
old.borrow_mut().prev = Some(Rc::downgrade(&node));
node.borrow_mut().next = Some(old);
self.head = Some(node);
}
None => {
self.tail = Some(Rc::clone(&node));
self.head = Some(node);
}
}
}
fn to_vec_forward(&self) -> Vec<i32> {
let mut out = Vec::new();
let mut cur = self.head.clone();
while let Some(n) = cur {
out.push(n.borrow().value);
cur = n.borrow().next.clone();
}
out
}
fn to_vec_backward(&self) -> Vec<i32> {
let mut out = Vec::new();
let mut cur = self.tail.clone();
while let Some(n) = cur {
out.push(n.borrow().value);
cur = n.borrow().prev.as_ref().and_then(|w| w.upgrade());
}
out
}
}
fn main() {
let mut l = List::default();
l.push_back(2); l.push_back(3); l.push_front(1);
assert_eq!(l.to_vec_forward(), vec![1, 2, 3]);
assert_eq!(l.to_vec_backward(), vec![3, 2, 1]);
}prev must be Weak because otherwise every adjacent pair of nodes would hold strong
references to each other — a two-node cycle that never drops, leaking the entire list.
Worth noting: this is a well-known exercise, and the honest conclusion is that
Rc<RefCell<Node>> linked lists are the wrong data structure in Rust. Real code uses
Vec with integer indices (an arena) or std::collections::VecDeque. Do the exercise for
the understanding; don't ship it.
Self-check
- Why does a recursive enum need
Box? - Why is
Rc::clone(&a)preferred overa.clone()? - What does
RefCellmove from compile time to runtime, and what's the penalty for breaking the rules? - When must a back-reference be
Weak? - What is deref coercion and where does it apply?
Answers
- Without indirection the type's size would be infinite;
Boxis one pointer of known size. - It signals a cheap refcount increment rather than a deep copy.
- Borrow checking; violating the rules panics at runtime instead of failing to compile.
- Whenever following both directions would create a cycle of strong references.
- Automatic conversion of
&Tto&UwhenT: Deref<Target = U>, applied at function call sites and method resolution.
