ownership
Rust Recursive types with Box
A recursively embedded value would have no finite size if each node contained the next node directly. Indirection gives the recursive field a known size. Use this model for teaching recursive structures; a vector is often simpler for ordinary lists. Expected output (not executed): 10 Why: Each boxed tail is an indirectly stored List; recursion ends at End. Common mistake: Using unbounded recursive traversal for arbitrarily deep input without considering stack exhaustion.
Formal Syntax & Structure
rust syntaxrust
enum List { End, Node(u32, Box<List>) }Working Example
Example Snippetrust
enum List { End, Node(u32, Box<List>) }fn sum(list: &List) -> u32 { match list { List::End => 0, List::Node(n, rest) => n + sum(rest), }}fn main() { let list = List::Node(4, Box::new(List::Node(6, Box::new(List::End)))); println!("{}", sum(&list));}