typestar

Box and recursive types in Rust

Heap allocation that makes a recursive enum sized.

enum List {
    Cons(i32, Box<List>),
    Nil,
}

fn sum(list: &List) -> i32 {
    match list {
        List::Cons(v, rest) => v + sum(rest),
        List::Nil => 0,
    }
}

fn main() {
    let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
    println!("{}", sum(&list));
}

How it works

  1. Box<List> gives the recursive variant a known size.
  2. match walks the cons list to sum it.
  3. Box::new moves a value to the heap.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
256
Tokens
106
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 64 seconds.

Type this snippet

Step 1 of 2 in Smart pointers, step 13 of 15 in Ownership & borrowing.

← Previous Next →