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
Box<List>gives the recursive variant a known size.matchwalks the cons list to sum it.Box::newmoves a value to the heap.
Keywords and builtins used here
BoxListenumfni32letmainmatchsum
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.
Step 1 of 2 in Smart pointers, step 13 of 15 in Ownership & borrowing.