A linked list written as a plain enum does not compile: recursive type has infinite size. Reusing one list as the tail of two others gives E0382, changing a shared value gives E0596, and sending that value to a thread gives E0277. These errors come from two constraints. One is that a value placed on the stack must have a size known at compile time. The other is the rule this series started with: every value has one owner, there can be many shared references or one mutable reference at a time, and the compiler checks both.
A smart pointer is a type that dereferences like a pointer (Deref) and cleans up when it leaves scope (Drop). Box lifts the size constraint by putting the value on the heap. The ownership and borrowing rule is relaxed by the rest: Rc allows several owners, RefCell moves borrow checking to run time, and Arc and Mutex do the same across threads. None of this is free. The cost shows up as a heap allocation, count updates, a run-time panic, or waiting on a lock. Every example below was compiled with rustc 1.94.1, edition 2021, and run on aarch64-apple-darwin (Apple Silicon macOS). Sizes are for a 64-bit target.
Box — the value on the heap, still one owner
Box<T> allocates a T on the heap and keeps its address on the stack. Ownership works as it does for any value: one owner, assignment moves, and when the owner goes away the heap value is freed.
use std::mem::size_of;
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
fn main() {
println!("Box<i32> = {} bytes", size_of::<Box<i32>>());
println!("Box<[u8; 1024]> = {} bytes", size_of::<Box<[u8; 1024]>>());
let n = Box::new(5);
println!("*n + 1 = {}", *n + 1);
let a = Box::new(Noisy("a"));
let b = a;
println!("moved a into b");
drop(b);
println!("end of main");
}
Box<i32> = 8 bytes
Box<[u8; 1024]> = 8 bytes
*n + 1 = 6
moved a into b
drop a
end of main
Whether it holds an i32 or a 1024-byte array, a Box is one pointer, 8 bytes. Because Box implements Deref, *n uses the heap value like a plain value. Moving a into b copies only the 8-byte pointer, and Noisy’s Drop ran once, at drop(b). It printed before end of main, so the value was freed the moment b went away. Box’s own Drop drops the inner value and returns the heap memory.
So far there is no reason to put anything on the heap. The reason shows up with values whose size cannot be fixed at compile time, like shape at the bottom of the figure and the recursive type in the next section.
Recursive types — a pointer gives the type a size
To place values on the stack, the compiler works out each type’s size at compile time. For an enum that contains itself, that calculation never ends.
enum List {
Cons(i32, List),
Nil,
}
fn main() {
let _list = List::Cons(1, List::Nil);
}
error[E0072]: recursive type `List` has infinite size
--> list_err.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>),
| ++++ +
The output also included E0391 (computing whether List needs drop loops back on itself), which comes from the same cause; I left it out. The size of Cons is an i32 plus a List, and that List is again an i32 plus a List. Switch to Box<List> as the compiler suggests, and Cons holds a pointer instead.
use std::mem::size_of;
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
fn sum(list: &List) -> i32 {
match list {
Cons(value, rest) => value + sum(rest),
Nil => 0,
}
}
fn main() {
let list = Cons(1, Box::new(Cons(2, Box::new(Nil))));
println!("sum = {}", sum(&list));
println!("List = {} bytes", size_of::<List>());
}
sum = 3
List = 16 bytes
List is now 16 bytes — room for an i32 and a pointer. How those bytes are laid out, including how Cons and Nil are told apart, is for the next post. However many nodes there are, one List stays the same size, and the next node lives on the heap.
Box<dyn Trait> — differently sized types in one Vec
The traits, generics, and dyn post showed that dyn Trait has no size known at compile time, so it has to be used through a pointer such as & or Box, and measured Box<dyn Shape> at 16 bytes. What matters here is ownership. &dyn Trait points at a borrowed value, while Box<dyn Trait> owns it. It lets a Vec hold values of different types and free them itself.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
struct Circle(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
impl Shape for Circle {
fn area(&self) -> f64 {
3.14 * self.0 * self.0
}
}
impl Drop for Square {
fn drop(&mut self) {
println!("drop Square");
}
}
impl Drop for Circle {
fn drop(&mut self) {
println!("drop Circle");
}
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0)), Box::new(Circle(1.0))];
let total: f64 = shapes.iter().map(|shape| shape.area()).sum();
println!("total = {total:.2}");
drop(shapes);
println!("end of main");
}
total = 7.14
drop Square
drop Circle
end of main
A single drop(shapes) ran Drop for Square and then Circle. The Vec drops each Box<dyn Shape> element, and each Box calls the concrete type’s Drop through the drop function in its vtable before returning the heap memory. The shape in the first figure is that data pointer and vtable pointer.
Rc — more than one owner
A Box has one owner, so using the same list as the tail of two lists fails on the second use.
#[derive(Debug)]
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
fn main() {
let shared = Cons(5, Box::new(Cons(10, Box::new(Nil))));
let b = Cons(3, Box::new(shared));
let c = Cons(4, Box::new(shared));
println!("{b:?} {c:?}");
}
error[E0382]: use of moved value: `shared`
--> box_share_err.rs:12:30
|
10 | let shared = Cons(5, Box::new(Cons(10, Box::new(Nil))));
| ------ move occurs because `shared` has type `List`, which does not implement the `Copy` trait
11 | let b = Cons(3, Box::new(shared));
| ------ value moved here
12 | let c = Cons(4, Box::new(shared));
| ^^^^^^ value used here after move
|
note: if `List` implemented `Clone`, you could clone the value
--> box_share_err.rs:2:1
|
2 | enum List {
| ^^^^^^^^^ consider implementing `Clone` for this type
...
11 | let b = Cons(3, Box::new(shared));
| ------ you could clone this value
The compiler suggests Clone, but that gives two copies of the list. To have two owners share one copy, use Rc<T> (reference counted).
use std::rc::Rc;
enum List {
Cons(i32, Rc<List>),
Nil,
}
use List::{Cons, Nil};
fn sum(list: &List) -> i32 {
match list {
Cons(value, rest) => value + sum(rest),
Nil => 0,
}
}
fn main() {
let shared = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
let b = Cons(3, Rc::clone(&shared));
let c = Cons(4, Rc::clone(&shared));
println!("b = {}, c = {}", sum(&b), sum(&c));
println!("shared strong = {}", Rc::strong_count(&shared));
}
b = 18, c = 19
shared strong = 3
Rc::new allocates the value on the heap together with two counts: the strong count, the number of Rcs that own the value, and the weak count, the number of Weaks covered later. Rc::clone copies nothing; it makes one more pointer and increments the strong count. shared, the Rc inside b, and the Rc inside c all point at the same allocation, so the strong count is 3. shared.clone() would do the same thing, but I used the Rc::clone(&shared) form so it reads as something other than a deep copy.
I used Drop output to see when the strong count drops and when the value is freed.
use std::rc::Rc;
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
fn main() {
let a = Rc::new(Noisy("config"));
println!("after a: strong = {}", Rc::strong_count(&a));
let b = Rc::clone(&a);
println!("after b: strong = {}", Rc::strong_count(&a));
{
let c = Rc::clone(&a);
println!("after c: strong = {}", Rc::strong_count(&c));
}
println!("c dropped: strong = {}", Rc::strong_count(&a));
println!("same allocation = {}", Rc::ptr_eq(&a, &b));
drop(a);
println!("a dropped: strong = {}", Rc::strong_count(&b));
drop(b);
println!("end of main");
}
after a: strong = 1
after b: strong = 2
after c: strong = 3
c dropped: strong = 2
same allocation = true
a dropped: strong = 1
drop config
end of main
The value survives c leaving its scope, and it survives dropping a first. drop config printed once, when the last owner b went away and the strong count reached 0. There are three owners now, yet the value is still freed exactly once. What changed is who decides when: the count, at run time, instead of the compiler, by scope.
RefCell — changing a shared value
Rc only hands out shared references. Letting one of several owners change the value would break the borrow rules, so while there are several owners an Rc will not give out a &mut T.
use std::rc::Rc;
fn main() {
let shared = Rc::new(vec![1, 2]);
let other = Rc::clone(&shared);
other.push(3);
println!("{shared:?}");
}
error[E0596]: cannot borrow data in an `Rc` as mutable
--> rc_mut_err.rs:6:5
|
6 | other.push(3);
| ^^^^^ cannot borrow as mutable
|
= help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Vec<i32>>`
RefCell<T> allows the value inside to change through a shared &RefCell<T>. This is called interior mutability. It does not remove the borrow rules; it moves the check from compile time to run time.
borrow() returns a shared borrow, Ref, and borrow_mut() returns a mutable one, RefMut. The RefCell keeps a borrow state — how many shared borrows exist and whether a mutable one does — and checks it on every call.
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let log = Rc::new(RefCell::new(Vec::new()));
let writer = Rc::clone(&log);
writer.borrow_mut().push("start");
writer.borrow_mut().push("stop");
{
let first = log.borrow();
let second = log.borrow();
println!("readers: {first:?} {second:?}");
println!("borrow_mut while reading: {}", log.try_borrow_mut().is_err());
}
println!("borrow_mut after readers: {}", log.try_borrow_mut().is_ok());
}
readers: ["start", "stop"] ["start", "stop"]
borrow_mut while reading: true
borrow_mut after readers: true
What went in through writer shows up through log. Rc<RefCell<T>> is the pairing that lets several owners change the same value. While first and second were alive, try_borrow_mut returned Err; once the block ended and both were dropped, it returned Ok. The same reason explains why the two writer.borrow_mut() lines did not collide: each RefMut drops at the end of its statement.
Without try_, overlapping borrows compile and then panic while running.
use std::cell::RefCell;
fn main() {
let names = RefCell::new(vec![String::from("a")]);
let first = names.borrow();
names.borrow_mut().push(String::from("b"));
println!("{first:?}");
}
thread 'main' (59900242) panicked at refcell_panic.rs:6:11:
RefCell already borrowed
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
The number in parentheses is a thread ID and changes from run to run. With a plain Vec and an ordinary reference instead, the compiler rejects the same code with E0502 from the references and borrowing post. RefCell turned that error into a panic. It allows patterns the compiler cannot prove safe and checks the unproven part while the program runs, paying for the stored borrow state and a check on every call.
Reference cycles — a leak built from Rc
With Rc<RefCell<T>>, values can point at each other. When two nodes point at each other through Rc, the strong count never reaches 0.
use std::cell::RefCell;
use std::rc::Rc;
struct Node {
name: &'static str,
next: RefCell<Option<Rc<Node>>>,
}
impl Drop for Node {
fn drop(&mut self) {
println!("drop {}", self.name);
}
}
fn main() {
let a = Rc::new(Node { name: "a", next: RefCell::new(None) });
let b = Rc::new(Node { name: "b", next: RefCell::new(Some(Rc::clone(&a))) });
*a.next.borrow_mut() = Some(Rc::clone(&b));
let watch_a = Rc::downgrade(&a);
let watch_b = Rc::downgrade(&b);
println!("a strong = {}, b strong = {}", Rc::strong_count(&a), Rc::strong_count(&b));
drop(a);
drop(b);
println!("after drop: a strong = {}, b strong = {}", watch_a.strong_count(), watch_b.strong_count());
println!("end of main");
}
a strong = 2, b strong = 2
after drop: a strong = 1, b strong = 1
end of main
Neither drop a nor drop b ever printed. After the variables a and b were dropped, the Weak handles made beforehand showed a strong count of 1 for each. That last 1 is held by the other node’s next. Nothing in the program can reach either node anymore, and neither is freed. That is a memory leak — one that builds up while the program runs, since the operating system reclaims everything when the process exits.
There is no unsafe in this code. The Rust Book says preventing memory leaks entirely is not one of Rust’s guarantees, and that leaks are memory safe. Freed memory is never read; memory just never gets freed. Once a count decides when to free, I take it that avoiding cycles becomes the job of whoever writes the code.
Weak — a reference that leaves the strong count alone
To break a cycle, turn one direction into a reference that does not own. Rc::downgrade makes a Weak<T>, which increments the weak count instead of the strong count. A Weak does not keep the value alive. Getting at the value takes a call to upgrade(), which returns an Option<Rc<T>> and is None once the value is gone. In a tree, a parent owns its children and each child points at its parent with a Weak.
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct Node {
name: &'static str,
parent: RefCell<Weak<Node>>,
children: RefCell<Vec<Rc<Node>>>,
}
impl Drop for Node {
fn drop(&mut self) {
println!("drop {}", self.name);
}
}
fn main() {
let leaf = Rc::new(Node {
name: "leaf",
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![]),
});
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade().map(|p| p.name));
{
let branch = Rc::new(Node {
name: "branch",
parent: RefCell::new(Weak::new()),
children: RefCell::new(vec![Rc::clone(&leaf)]),
});
*leaf.parent.borrow_mut() = Rc::downgrade(&branch);
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade().map(|p| p.name));
println!("branch children = {}", branch.children.borrow().len());
println!("branch strong = {}, weak = {}", Rc::strong_count(&branch), Rc::weak_count(&branch));
println!("leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf));
}
println!("leaf parent = {:?}", leaf.parent.borrow().upgrade().map(|p| p.name));
println!("leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf));
}
leaf parent = None
leaf parent = Some("branch")
branch children = 1
branch strong = 1, weak = 1
leaf strong = 2, weak = 0
drop branch
leaf parent = None
leaf strong = 1, weak = 0
drop leaf
Inside the block, branch has a strong count of 1 (the variable branch) and a weak count of 1 (leaf.parent), and leaf has a strong count of 2 (the variable leaf and branch.children). When the block ended, branch’s strong count went to 0 and drop branch printed; the remaining weak count did not prevent it. After that, upgrade() returned None, and with branch.children gone, leaf’s strong count fell to 1. Unlike the cycle example, drop leaf printed too, as main ended.
Arc and Mutex — sharing across threads
Sending an Rc to a thread does not compile.
use std::rc::Rc;
use std::thread;
fn main() {
let counter = Rc::new(0);
let handle = thread::spawn(move || {
println!("{counter}");
});
handle.join().unwrap();
}
error[E0277]: `Rc<i32>` cannot be sent between threads safely
--> rc_thread_err.rs:6:32
|
6 | let handle = thread::spawn(move || {
| ------------- ^------
| | |
| __________________|_____________within this `{closure@rc_thread_err.rs:6:32: 6:39}`
| | |
| | required by a bound introduced by this call
7 | | println!("{counter}");
8 | | });
| |_____^ `Rc<i32>` cannot be sent between threads safely
|
= help: within `{closure@rc_thread_err.rs:6:32: 6:39}`, the trait `Send` is not implemented for `Rc<i32>`
note: required because it's used within this closure
--> rc_thread_err.rs:6:32
|
6 | let handle = thread::spawn(move || {
| ^^^^^^^
note: required by a bound in `spawn`
--> …/library/std/src/thread/functions.rs:128:8
|
125 | pub fn spawn<F, T>(f: F) -> JoinHandle<T>
| ----- required by a bound in this function
...
128 | F: Send + 'static,
| ^^^^ required by this bound in `spawn`
I shortened the standard library path. thread::spawn puts a Send bound on the closure. Send marks a value as safe to move to another thread, and a closure is Send only when all its fields are. The std docs say Rc uses non-atomic reference counting, which keeps the overhead low but means it cannot be sent between threads, so it does not implement Send. If two threads incremented the same count at once, one increment could be lost.
Across threads the type to use is Arc<T> (Atomically Reference Counted). It updates the count with atomic operations and is otherwise used like Rc. But Arc also hands out only shared references, so changing the value needs interior mutability, and putting a RefCell inside fails to compile again.
use std::cell::RefCell;
use std::sync::Arc;
use std::thread;
fn main() {
let counter = Arc::new(RefCell::new(0));
let worker = Arc::clone(&counter);
let handle = thread::spawn(move || {
*worker.borrow_mut() += 1;
});
handle.join().unwrap();
}
error[E0277]: `RefCell<i32>` cannot be shared between threads safely
--> arc_refcell_err.rs:8:32
|
8 | let handle = thread::spawn(move || {
| __________________-------------_^
| | |
| | required by a bound introduced by this call
9 | | *worker.borrow_mut() += 1;
10 | | });
| |_____^ `RefCell<i32>` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `RefCell<i32>`
= note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead
= note: required for `Arc<RefCell<i32>>` to implement `Send`
note: required because it's used within this closure
--> arc_refcell_err.rs:8:32
|
8 | let handle = thread::spawn(move || {
| ^^^^^^^
note: required by a bound in `spawn`
--> …/library/std/src/thread/functions.rs:128:8
|
125 | pub fn spawn<F, T>(f: F) -> JoinHandle<T>
| ----- required by a bound in this function
...
128 | F: Send + 'static,
| ^^^^ required by this bound in `spawn`
This time Sync is missing. By the std docs’ definition, T is Sync exactly when &T is Send, meaning several threads may hold &T at once. Arc<T> is Send only when T is both Send and Sync. A RefCell is Send when its contents are, so it can move to another thread whole, but its borrow state is only kept correct within one thread, so it is not Sync. The error’s second note spells out that link. The RwLock the compiler suggests would also work; this post uses Mutex<T>.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for _ in 0..4 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
for _ in 0..1000 {
*counter.lock().unwrap() += 1;
}
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("strong after join = {}", Arc::strong_count(&counter));
println!("counter = {}", *counter.lock().unwrap());
}
strong after join = 1
counter = 4000
Four threads adding 1000 each gave 4000. Each thread took its own counter, made with Arc::clone, through move, and that Arc dropped when the thread finished, so the strong count is 1 after the joins. lock() waits while another thread holds the lock and then returns a MutexGuard. The guard plays the part RefMut played, and dropping it releases the lock. Where RefCell refused overlapping borrows with a panic, Mutex makes the caller wait. Waiting has its own cost: the std docs say that if the thread holding the lock calls lock() again, that call will not return (it may deadlock or panic). The unwrap() handles the error returned when a thread panicked while holding the lock, which this post does not cover.
Mutex<T> is Sync as long as T is Send, because the lock lets only one thread at a time reach the value. That makes Arc<Mutex<i32>> Send, and it passes spawn. Arc and Mutex do across threads what Rc and RefCell did within one, paying with atomic operations and waiting on the lock.
Choosing a pointer
Each of the five types lifts something different. Box keeps the ownership and borrowing rules and lifts only the size constraint. Rc and Arc allow several owners and let a count decide when to free. RefCell and Mutex keep the borrow rules but defer the check to run time. Crossing threads turns Rc into Arc and RefCell into Mutex.
The order I settled on: plain values and references when they are enough, Box when size is the problem, Rc and RefCell only when several owners or mutation while shared are really needed, and Arc and Mutex only when the value has to cross threads. Each step later in that order pays more at run time.
Wrapping up
Some things held even as owners multiplied and checks moved to run time. Rc gave the value three owners, yet drop config printed once, and RefCell still refused overlapping borrows; the RefCell already borrowed panic did the refusing instead of the compiler. What changed was when the check happens and what it costs. Rc, which lets a count decide when to free, never freed either node in the cycle, and a Weak had to break that cycle by hand because the compiler does not catch it. The next post picks up what this one deferred: the size of wrappers like Rc, RefCell, and Mutex, and how an enum like List is laid out in memory.
References
- Rust Memory Layout and Allocation: wrapper sizes and how enums like
Listare laid out - Rust Traits, Generics, and dyn:
dyn Trait, vtables, fat pointers - Rust References and Borrowing: the rule that shared and mutable borrows cannot overlap
- Rust Ownership and Freeing Memory: one owner, dropped at the end of its scope
- Rust Closures and Iterators:
moveclosures and capture - The Rust Programming Language — Smart Pointers
- The Rust Programming Language — Reference Cycles Can Leak Memory
- The Rust Programming Language — Shared-State Concurrency
std::rcstd::cellstd::sync::Arcstd::sync::Mutexstd::marker::Sync