Skip to content
Justice Tech School

Box and the Heap

Box<T> stores a value on the heap. Needed for recursive types and trait objects.

Example
enum List { Cons(i32, Box<List>), Nil }
fn sum(l: &List) -> i32 { match l { List::Cons(v, n) => v + sum(n), List::Nil => 0 } }

fn main() {
    let b = Box::new(5);
    println!("{}", *b + 1);
    let l = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
    println!("{}", sum(&l));
}

Result

6
3

Exercise

Heap allocation.

::new(5)

Quiz Test

Why Box for recursive types?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.