Sub topic 15
Box: owning heap data
This chapter assumes you know basic Rust syntax, can build and run programs with cargo, and understand the move rules from earlier chapters. You should also know the general difference between the stack and the heap, and be comfortable with String, Vec, and &str.
What Box is
Box<T> is a smart pointer that owns one value of type T stored on the heap. The box itself is a pointer-sized value that lives wherever you put it, often on the stack. The T it points to lives on the heap.
Box follows the ownership rules like any other owner:
- A box has exactly one owner at a time.
- Assigning or passing a box moves it.
- When the owner goes out of scope, Rust drops the box. That drops the contained value and frees the heap memory.
You never call free. Box is the simplest case of "owning heap data". String and Vec<T> work the same way internally, but they also manage a buffer that can grow.
fn main() {
let b = Box::new(5);
println!("b = {b}");
let sum = *b + 1;
println!("sum = {sum}");
}Box::new(5) allocates space for an i32 on the heap and moves 5 into it. *b dereferences the box to reach the value. Printing works without an explicit * because Box<T> implements Display when T does. When b goes out of scope at the end of main, the heap memory is freed.
Moves and Drop with Box
A box moves like a String does. After a move, the old variable is unusable, and the heap allocation is freed exactly once, by the new owner.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn consume(b: Box<Noisy>) {
println!("consuming {}", b.0);
}
fn main() {
let a = Box::new(Noisy("a"));
let b = Box::new(Noisy("b"));
consume(a);
println!("after consume");
let _keep = b;
println!("main ends");
}This prints:
consuming a
dropping a
after consume
main ends
dropping bconsume takes ownership of a, so a is dropped when consume returns. Using a after the call would be a compile error. The value b moves into _keep, which lives until the end of main.
When you need Box
Most Rust code does not need Box. Vectors, strings, and plain structs already handle their own memory. Reach for Box in these situations.
- Recursive types. The compiler must know the size of every type. A type that contains itself directly has infinite size.
- Trait objects. A
Box<dyn Trait>holds a value whose concrete type is only known at run time. - Large values you want to move cheaply. Moving a
Box<T>copies one pointer instead of the wholeT. - Transferring ownership of heap data through an interface that needs a single fixed-size handle.
Recursive types
This definition fails to compile:
enum List {
Cons(i32, List),
Nil,
}The compiler reports "recursive type List has infinite size". A List would contain an i32 and another List, which contains another List, and so on. Wrapping the recursive part in a Box fixes this, because a box has a known size (one pointer) no matter what it points to.
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(Cons(3, Box::new(Nil))))));
println!("sum = {}", sum(&list));
}The match on &List binds value as &i32 and rest as &Box<List>. Passing rest to sum works because of deref coercion, which turns &Box<List> into &List automatically.
Each Cons owns the next node through its box. When list goes out of scope, Rust drops the first node, which drops its box, which drops the next node, and so on down to Nil. The whole chain is freed with no explicit code.
The diagram below shows the layout of this list.
Trait objects
A Vec needs every element to have the same size. A Box<dyn Trait> has a fixed size (a pointer plus a pointer to a method table), so you can store different concrete types behind the same trait in one collection.
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 {
std::f64::consts::PI * self.0 * self.0
}
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0)), Box::new(Circle(1.0))];
for s in &shapes {
println!("{:.2}", s.area());
}
}Each box owns its shape. When shapes is dropped, every box is dropped, and each value's own destructor runs even though the vector does not know the concrete types.
Dereferencing and moving out of a box
*b reads the contained value. For Copy types such as i32, this copies the value. For other types, *b used by value moves the contents out of the box, and the box can no longer be used.
fn main() {
let b = Box::new(String::from("hello"));
let s: String = *b; // moves the String out; b is now unusable
println!("{s}");
// println!("{b}"); // error: borrow of moved value: `b`
}Box is the one pointer type where this move-out-of-deref is allowed. References, Rc, and others do not allow it, because they do not own the value exclusively.
You can also mutate through a box if the binding is mut:
fn main() {
let mut b = Box::new(10);
*b += 5;
println!("{b}");
}Box versus a reference
| Aspect | `Box<T>` | `&T` or `&mut T` |
|---|---|---|
| Owns the value | Yes | No |
| Where the value lives | Heap | Anywhere |
| Freed when | The box is dropped | Never (the owner frees it) |
| Needs a lifetime | No | Yes, checked by the compiler |
| Can be returned from a function | Yes, freely | Only if it points to data that outlives the call |
The last row matters most in practice. A function cannot return a reference to one of its local variables, but it can return a Box holding a new value, because ownership moves out to the caller.
fn make_greeting(name: &str) -> Box<String> {
Box::new(format!("hello, {name}"))
}
fn main() {
let g = make_greeting("Ada");
println!("{g}");
}In everyday code you would return a plain String here. The String already owns heap data, so boxing it only adds a second allocation. The example shows the ownership transfer, not a recommended style.
Common mistakes
- Boxing needlessly.
Box<i32>orBox<String>is rarely useful. AVecorStringis already heap-backed and cheap to move. - Boxing a reference.
Box<&T>is a box that owns a borrowed value. It does not give the reference ownership of the data. - Forgetting the box in a recursive type. The "infinite size" error always means a type contains itself without an indirection such as
Box,Vec, or a reference. - Expecting
Boxto be shareable. A box has one owner. If you need several owners, the next chapter's tool isRc.
Exercises
Exercise
Why does enum List { Cons(i32, List), Nil } fail to compile, and what is the smallest change that fixes it?
Show answer
A List would contain another List directly, so its size would be infinite. Wrapping the recursive field in a box, Cons(i32, Box<List>), fixes it because a Box has a fixed pointer size regardless of what it points to.
Exercise
What does this program print, and why? fn main() { let a = Box::new(String::from("x")); let b = a; println!("{b}"); println!("{a}"); }
Show answer
It does not compile. let b = a; moves the box into b, so the last line uses a moved value (error: borrow of moved value: a). Removing the last line makes it print x.
Exercise
You need a Vec holding both Square and Circle values that implement a Shape trait. What element type do you use, and who frees each shape?
Show answer
Use Vec<Box<dyn Shape>>. Each box owns its shape, so when the vector is dropped it drops every box, and each box runs the destructor of its concrete value and frees its heap memory.