Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 132 ยท Ownership and Borrowing

Box and the Heap

Learn Rust Box<T> for heap allocation: recursive types like linked lists and expression trees, trait objects, Deref, deref coercion and drop order.

So far every value in this tutorial lived on the stack or inside a String or Vec that managed its own heap memory. Sometimes you want to put a single value on the heap yourself. The simplest tool for that is Box<T>: a smart pointer that owns one T stored on the heap and frees it automatically when the box goes out of scope.

A smart pointer is a type that acts like a pointer but has extra behaviour, usually ownership and cleanup. Box is the smallest and most common one. This lesson covers what it is, when you need it (recursive types, trait objects, moving big values cheaply), how the Deref trait lets Box and other pointers behave like references, how deref coercion saves typing, and in what order Rust drops things. Shared ownership (Rc, Arc) and interior mutability come in the Smart Pointers chapter, starting with Rc, Arc and Shared Ownership.

Creating a Box

Box::new(value) moves the value onto the heap and gives you the box. You use the contents through the box with * or automatically through method calls:

Rust Your first Box

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A Box<i32> is a bad idea in real code (an i32 is cheaper on the stack), but it makes the mechanics clear. The Box itself is one pointer (8 bytes on 64-bit); the value lives elsewhere.

Where things live

Rust The size of a Box does not depend on its contents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Three useful facts appear: a Box<T> is pointer-sized; Box<[T]> and Box<str> are fat (pointer plus length) because they hold unsized data; and Option<Box<T>> is no bigger than the Box itself, because a box can never be null, so Rust uses the null address to represent None. This is called the niche optimization.

Dropping is automatic

When a Box goes out of scope, the value inside is dropped and the heap memory freed. There is no free to forget and no double free, because ownership is unique:

Rust A Box frees its contents at scope end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

When do you actually need Box?

Rust code uses Box less than newcomers expect. Reach for it in these situations:

  1. A recursive type whose size would otherwise be infinite (lists, trees).
  2. A trait object: Box<dyn Trait>, to hold different types behind one interface.
  3. Moving a large value cheaply: passing a Box<BigStruct> copies only a pointer. (Moves of big stack values are bit-copies; the optimizer often removes them, so measure first.)
  4. Ownership of unsized data: Box<[T]>, Box<str>.
  5. Heap placement on purpose: very large arrays that would overflow the stack, or data that must keep a stable address.

If none of these apply, use plain values, Vec or String.

Recursive types

Try to define a linked list the obvious way:

Rust A type that contains itself (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0072]: recursive type `List` has infinite size
 --> main.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>),
  |               ++++    +

A List would contain an i32 and a List, which contains an i32 and a List... the compiler cannot compute a size. A Box<List> has a known size (one pointer), so the type is finite. The message offers the cure:

Rust A cons list with Box

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The Debug output shows the nesting: Cons(1, Cons(2, Cons(3, Nil))). Every Box here is invisible in the printout but is a separate heap allocation. Singly linked lists are a poor data structure for real work (each node is an allocation, traversal chases pointers and misses the cache), and Vec almost always wins. They remain the classic way to learn ownership; a larger example appears in Building Data Structures with Unsafe.

A mutable linked list with Option<Box>

The usual real-world form uses a struct and Option<Box<Node>>, which is nullable thanks to the niche optimization:

Rust A stack made of boxed nodes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Look at how Option::take (from Copy, Clone and Move Semantics) moves the old head out of &mut self so it can become the new node's next. Without it you would hit "cannot move out of borrowed content".

An expression tree

Trees are naturally recursive: every operator node owns its children. Enums plus Box model abstract syntax trees neatly:

Rust Evaluating an expression tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Note how eval(a) takes &Box<Expr> where &Expr is expected. That works because of deref coercion, explained below.

Trait objects: a preview

Types of different sizes cannot sit in one Vec by value, but pointers are all the same size. Box<dyn Trait> is a pointer to some value implementing a trait, plus a table of that type's methods (a vtable), so calls are resolved at run time:

Rust A Vec of different shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Box<dyn Shape> is a fat pointer (data pointer plus vtable pointer, 16 bytes). Details, costs and the alternatives (generics) are in Trait Objects and Dynamic Dispatch.

Deref: making pointers feel like references

*boxed works because Box<T> implements the Deref trait, which says "when someone writes *x, give them a reference to the inner value". You can implement it for your own smart pointers:

Rust Our own smart pointer with Deref and DerefMut

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Deref gives read access (&T), DerefMut gives write access (&mut T). When you write *w, the compiler turns it into *Deref::deref(&w); for assignment it uses deref_mut.

Deref is meant for smart pointers. Do not implement it just to get "inheritance" of methods from another type; that surprises readers and breaks method resolution in subtle ways. Wrap and forward explicitly, or use composition and traits.

Deref coercion

Deref gives Rust a convenient trick: when a function expects &U and you pass &T where T: Deref<Target = U>, the compiler inserts as many deref calls as needed. You have been relying on it already:

You pass Function expects Works because
&String &str String: Deref<Target = str>
&Vec<T> &[T] Vec<T>: Deref<Target = [T]>
&Box<T> &T Box<T>: Deref<Target = T>
&Box<String> &str two steps: Box<String> to String to str
Rust Deref coercion chains

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Coercion also goes from &mut T to &U (never the other way, which would let you gain write access out of nowhere) and from &mut T to &mut U when T: DerefMut. It happens at compile time and costs nothing.

Drop order and std::mem::drop

Every value is dropped when its owner goes out of scope. The order is predictable:

  • Local variables are dropped in reverse order of declaration (last declared, first dropped).
  • Struct fields are dropped in declaration order, after the struct's own Drop::drop ran.
  • Vec elements are dropped in order, first to last.
  • Temporaries are dropped at the end of the statement that created them.
Rust Drop order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Note the difference between _name and _: let _a = ... keeps the value alive until the end of scope, while let _ = ... does not bind it and drops it at once. This matters for guards such as mutex locks.

Dropping early

You cannot call value.drop() yourself (the compiler forbids it, as it would lead to a double drop at scope end). To release something early, move it into std::mem::drop, which is simply a function that takes ownership and does nothing:

Rust Explicit early drop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

drop is in the prelude, so no import is needed. Typical uses are releasing a lock guard, closing a file before reopening it, or ending a borrow explicitly. The full story of the Drop trait and RAII is in Drop and RAII.

Box::leak and std::mem::forget skip the drop on purpose. They are safe functions, but leaks are rarely what you want; use them for data that must live until the program ends ('static).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Box<T> store?

    Box is a unique owning pointer to a heap allocation. The value is dropped and the memory freed when the Box goes out of scope.
  2. 2. Why does enum List { Cons(i32, List), Nil } fail with E0072?

    Without indirection the compiler cannot compute a size. Cons(i32, Box<List>) has a finite size because a Box is a pointer.
  3. 3. Why is size_of::<Option<Box<i32>>>() equal to size_of::<Box<i32>>()?

    This niche optimization stores None as the null pointer, so no extra tag is needed.
  4. 4. Which call compiles when fn greet(name: &str) and let b = Box::new(String::from("x"));?

    &b is &Box<String>. Deref coercion turns it into &String and then &str. Passing b or *b would try to move a String, not borrow a str.
  5. 5. In what order are local variables a, b, c (declared in that order) dropped at the end of a scope?

    Locals are dropped in reverse order of declaration, like a stack unwinding.

Summary

  • Box<T> owns one value on the heap and frees it when dropped. It is one pointer wide; Box<[T]>, Box<str> and Box<dyn Trait> are two words wide.
  • Use it for recursive types (lists, trees, expression ASTs), trait objects, unsized data, and deliberately heap-allocated or large values. Otherwise prefer plain values, Vec and String.
  • Option<Box<T>> costs no more than Box<T> thanks to the niche optimization, which makes it the standard "nullable owning pointer".
  • Deref and DerefMut let *x and method calls reach the inner value; deref coercion converts &Box<String>, &String, &Vec<T> into &str / &[T] automatically.
  • Drop order: locals in reverse, fields in declaration order, Vec elements first to last; let _ = x drops immediately.
  • You cannot call .drop() yourself; move the value into drop(value) to release it early.

Next: Structs