Applied Intermediate
16 Smart pointers
Box gives a value a fixed-size home on the heap -- which is what makes recursive types possible. Rc adds shared ownership: several owners of one allocation, freed when the last one drops.
Sum the recursive List in sum. Box is what lets the type nest.
Hints
- Recurse on the tail: a node's total is its value plus the rest's total.
match list { List::Node(v, rest) => v + sum(rest), List::End => 0 }--&Box<List>coerces to&List.
Reveal solution
enum List {
Node(i32, Box<List>),
End,
}
fn sum(list: &List) -> i32 {
match list {
List::Node(v, rest) => v + sum(rest),
List::End => 0,
}
}