Box and recursive data
Quick answer
Box<T> owns a value through an allocation and releases it when the box is dropped. It is useful when the value needs indirection, especially when defining recursive data structures.
Why recursion needs indirection
A recursive enum cannot directly contain itself because its size would be unbounded. A box has a known size for a sized pointee, independent of the size of the stored value. Dereference a box using *; moving a box transfers ownership, not a deep copy of its contents. Zero-sized values need not allocate.
fn main() { let mut b = Box::new(8); *b += 2; let moved = b; println!("{}", *moved); }Expected stdout (not executed):
10The second binding owns the same boxed value.
enum List { Node(i32, Box<List>), End }fn sum(list: &List) -> i32 { match list { List::End => 0, List::Node(n, rest) => n + sum(rest) }}fn main() { let list = List::Node(3, Box::new(List::Node(5, Box::new(List::End)))); println!("{}", sum(&list)); }Expected stdout (not executed):
8Each next node has an indirect link, so the enum has finite size. This tiny example is not a deep-list algorithm.
Common mistake
Do not box every value by default; allocation and indirection have costs.
Try it yourself
Add another node with value 2 and predict the sum.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Box and recursive data — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
Why does a linked-list node store its recursive next node indirectly?
Box and recursive data — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let mut b = Box::new(8); *b += 2; let moved = b; println!("{}", *moved); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Box and recursive data — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust enum List { Node(i32, Box<List>), End } fn sum(list: &List) -> i32 { match list { List::End => 0, List::Node(n, rest) => n + sum(rest) } } fn main() { let list = List::Node(3, Box::new(List::Node(5, Box::new(List::End)))); println!("{}", sum(&list)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.