Sub topic 15
Box: owning heap data
This chapter assumes you know the ownership rules, moves, and the Drop trait from earlier chapters. It also assumes you know that the stack holds fixed-size values and the heap holds data whose size can vary.
What Box is
Box<T> is a smart pointer that owns one value of type T on the heap. The box itself is a pointer-sized value on the stack. It has exactly one owner, so every ownership rule applies. When the owner goes out of scope, Rust drops the heap value and frees its memory.
fn main() {
let b = Box::new(5);
println!("b = {b}");
let c = *b + 1;
println!("c = {c}");
}Box::new allocates the value on the heap. The * operator dereferences the box to reach the value inside. At the end of main, b is dropped and the allocation is released. You never call a free function.
Moving a box
Assigning a box to another variable, or passing it to a function, moves ownership. Only the pointer is copied. The heap data stays where it is. The old variable becomes invalid, which prevents a double free.
This makes Box a cheap way to move a large value. Moving a large struct copies all its bytes, while moving a Box of that struct copies one pointer.
Recursive types
The most common reason to reach for Box is a recursive type. A type that contains itself directly would have infinite size, so the compiler rejects it. A Box has a fixed size, so it fixes the problem.
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
fn main() {
let list = Cons(1, Box::new(Cons(2, Box::new(Nil))));
if let Cons(head, _) = &list {
println!("{head}");
}
}Each Cons holds an i32 and a pointer, so the compiler knows its size. Each node owns the next one. When list is dropped, Rust drops the whole chain.
Other uses
- Trait objects:
Box<dyn Trait>stores values of different concrete types behind one type. - Large values: boxing keeps moves cheap and the stack small.
- Unknown size at compile time: the pointer's size is known even when the target's is not.
Common errors
Using a box after moving it gives "borrow of moved value". Fix it by borrowing (&b) or by cloning (b.clone()) if T implements Clone. A recursive type without a Box gives "recursive type has infinite size". Wrap the recursive field in Box<...>.
Exercise
Why does enum List { Cons(i32, List), Nil } fail to compile, and what is the smallest change that fixes it?
Show answer
List would contain another List directly, so its size would be infinite. Changing the field to Box<List> fixes it, because a Box is a pointer with a known size and the next node lives on the heap.