Sub topic 3
Box<T>: putting a value on the heap
This chapter covers Box<T>, the simplest smart pointer in Rust. It assumes you know Rust ownership, moves, and borrowing, basic traits and generics, and the difference between the stack and the heap. Recursive types and trait objects get their own chapters. Here we focus on what a Box is, what it costs, and when to reach for one.
What Box<T> does
A Box<T> is a smart pointer that owns a value of type T stored on the heap. The box itself lives wherever you put it, usually on the stack. It holds one pointer to the heap allocation.
fn main() {
let b = Box::new(5);
println!("b = {b}");
}Here Box::new(5) allocates space for an i32 on the heap and moves 5 into it. The variable b holds the pointer. When b goes out of scope, Rust frees the heap memory. You never call free yourself.
A box has no runtime overhead beyond the allocation. It does not track reference counts or check borrows. It is a single owner, and the ownership rules you already know apply unchanged.
Ownership and moves
Because a Box owns its value, moving the box moves ownership. The heap data does not get copied. Only the pointer moves.
fn consume(b: Box<String>) {
println!("got {b}");
}
fn main() {
let boxed = Box::new(String::from("hello"));
consume(boxed);
// println!("{boxed}"); // error[E0382]: borrow of moved value
}Uncommenting the last line fails to compile, because boxed was moved into consume. A Box<T> is Copy never, and it is Clone only when T is Clone. Cloning a box allocates new heap memory and clones the contents.
Reading and moving the value out
A box behaves like a reference in many places, because it implements the Deref trait. The next chapters cover that trait in detail. For now, note that * reaches the value inside.
fn main() {
let mut b = Box::new(10);
*b += 1;
println!("{}", *b);
let moved_out: i32 = *b;
println!("{moved_out}");
}The program prints 11 and then 11. For i32, *b copies the value out. For a non-Copy type such as String, *b moves the value out of the box and consumes the box. Box is the one standard smart pointer that supports this move out of a dereference. Other pointers such as Rc do not.
fn main() {
let b = Box::new(String::from("data"));
let s: String = *b;
println!("{s}");
// b can no longer be used here
}When to use a Box
The Rust book gives three common reasons.
- A type whose size is unknown at compile time. A recursive type contains itself, so the compiler cannot compute its size. A box has a fixed pointer size, which breaks the loop.
- A large value you want to move without copying. Moving a big struct copies all its bytes on the stack. Moving a
Boxcopies one pointer. - Owning a value by trait rather than by concrete type.
Box<dyn Trait>lets you hold any type that implements a trait.
The first and third reasons are required by the language. The second is an optimization you should measure first. Moves of large values are often optimized away, and the allocation itself costs time.
Sizes: stack value versus box
You can see the difference with std::mem::size_of.
use std::mem::size_of;
fn main() {
println!("[i32; 1000] = {} bytes", size_of::<[i32; 1000]>());
println!("Box<[i32; 1000]> = {} bytes", size_of::<Box<[i32; 1000]>>());
println!("Box<i32> = {} bytes", size_of::<Box<i32>>());
}On a 64-bit platform this prints 4000, 8, and 8 bytes. The size of the box does not depend on T, as long as T has a size known at compile time.
A box can also point to data whose size is not known at compile time. Box<str>, Box<[T]>, and Box<dyn Trait> are "fat" pointers, which carry extra information: a length for slices and strings, or a vtable pointer for trait objects. On 64-bit platforms they occupy 16 bytes.
use std::mem::size_of;
fn main() {
println!("Box<i32> = {}", size_of::<Box<i32>>());
println!("Box<[i32]> = {}", size_of::<Box<[i32]>>());
println!("Box<dyn Send> = {}", size_of::<Box<dyn Send>>());
}This prints 8, 16, and 16 on a 64-bit target.
Box, references, and the stack
A box is not the same as a reference. A reference &T borrows a value that someone else owns, and the borrow checker ties its lifetime to the owner. A Box<T> owns its value, so it can be returned from a function without lifetime annotations.
fn make_counter() -> Box<i32> {
let n = 42;
Box::new(n)
}
fn main() {
let c = make_counter();
println!("{c}");
}Returning &n instead would not compile, because n is dropped when the function ends. Returning a Box moves ownership to the caller, and the heap data lives on.
Common errors and edge cases
- Boxing everything "for speed". A heap allocation is usually slower than keeping a value on the stack. Use a box when you need one of the three reasons above.
- Using a moved box. After
let s = *b;for a non-Copytype,bis unusable. The compiler reportsuse of moved value. - Expecting
Box::newto avoid a stack copy.Box::new(big_value)first buildsbig_valueon the stack and then moves it into the heap. For huge arrays this can overflow the stack in debug builds. Prefervec![0; N].into_boxed_slice()for large buffers. - Zero-sized types.
Box::new(())does not allocate. The box holds a dangling but well-aligned pointer, and nothing is freed. - Leaking on purpose.
Box::leakconsumes a box and returns a&'static mut T. The memory is never freed. This is safe, but it is a deliberate leak.
fn main() {
let leaked: &'static mut i32 = Box::leak(Box::new(7));
*leaked += 1;
println!("{leaked}");
}This prints 8. The heap integer lives until the program exits.
Summary of costs
| Property | `T` on the stack | `Box<T>` |
|---|---|---|
| Where the value lives | Stack | Heap |
| Size of the handle | `size_of::<T>()` | One pointer (two for unsized `T`) |
| Cost to create | None | One heap allocation |
| Cost to move | Copies all bytes of `T` | Copies the pointer |
| Number of owners | One | One |
| Mutation rules | Standard borrow rules | Standard borrow rules |
Exercise
What does the line let t: Box<[i32]> = vec![1, 2, 3].into_boxed_slice(); produce, and how many bytes does t itself occupy on a 64-bit platform?
Show answer
It produces a boxed slice that owns three i32 values on the heap. The variable t is a fat pointer holding the data address and the length, so it occupies 16 bytes on the stack.
Exercise
Why does let s: String = *b; compile for b: Box<String>, and what happens to b afterward?
Show answer
Box<T> supports moving the value out through *. The String moves to s, and b is treated as moved, so using it later is a compile error.