Box Indirection Enables Recursive Types
Recursive enums need a known size, so Box stores child nodes behind a heap pointer while match walks the owned tree to sum values and measure depth.
Code
// 递归类型必须有已知大小:Box 是指向堆上值的指针,枚举自身只存指针
#[derive(Debug)]
enum Tree {
Leaf(i64),
Node {
value: i64,
left: Box<Tree>,
right: Box<Tree>,
},
}
impl Tree {
fn sum(&self) -> i64 {
match self {
Tree::Leaf(v) => *v,
Tree::Node { value, left, right } => value + left.sum() + right.sum(),
}
}
fn depth(&self) -> usize {
match self {
Tree::Leaf(_) => 1,
Tree::Node { left, right, .. } => 1 + left.depth().max(right.depth()),
}
}
}
fn main() {
// 没有 Box 时 Rust 会报 E0072:递归类型的大小无法计算
let tree = Tree::Node {
value: 10,
left: Box::new(Tree::Leaf(4)),
right: Box::new(Tree::Node {
value: 25,
left: Box::new(Tree::Leaf(12)),
right: Box::new(Tree::Leaf(3)),
}),
};
println!("sum: {}", tree.sum());
println!("depth: {}", tree.depth());
println!("{tree:?}");
}How it works
Box Indirection Enables Recursive Types is built around the functions sum, depth and main.
Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Applying it
The primary signature is fn sum(&self) -> i64
The demo output is labeled (sum:, depth:), so every printed line maps back to its originating operation.
main is the driver: it invokes sum and depth before returning.
Statements that matter
fn depth(&self) -> usize {
match self {
Tree::Leaf(_) => 1,
Tree::Node { left, right, .. } => 1 + left.depth().max(right.depth()),
}
}
fn sum(&self) -> i64 {
match self {
Tree::Leaf(v) => *v,
Tree::Node { value, left, right } => value + left.sum() + right.sum(),
}
}
Interactive Tools for This Topic
Box Shadow GeneratorBuild CSS box-shadow values with offset, blur, spread, color, opacity, and inset controls, with a live preview of the result.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Box Indirection Enables Recursive Types print when run?
- The script runs standalone; its 2 labeled outputs include `sum:`, `depth:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.