capypad
0 day streak
rust / intermediate
Snippet

Box<T> for Heap Allocation and Recursive Types

Box<T> allocates data on the heap instead of the stack. This is essential for recursive data structures like trees and linked lists where the size cannot be known at compile time. Box<T> provides ownership semantics with fixed-size pointers.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
enum TreeNode<T> {
Leaf(T),
Branch {
value: T,
left: Box<TreeNode<T>>,
right: Box<TreeNode<T>>,
},
}
 
impl<T: std::fmt::Debug> TreeNode<T> {
fn new_leaf(value: T) -> Self {
TreeNode::Leaf(value)
}
fn new_branch(value: T, left: TreeNode<T>, right: TreeNode<T>) -> Self {
TreeNode::Branch {
value,
left: Box::new(left),
right: Box::new(right),
}
}
fn debug_print(&self, depth: usize) {
match self {
TreeNode::Leaf(v) => println!("{:width$}{:?}", "", v, width = depth * 2),
TreeNode::Branch { value, left, right } => {
println!("{:width$}{:?}", "", value, width = depth * 2);
left.debug_print(depth + 1);
right.debug_print(depth + 1);
}
}
}
}
Breakdown
1
left: Box<TreeNode<T>>
Box wraps recursive type, breaking infinite size at compile time
2
Box::new(left)
Converts stack-allocated TreeNode to heap-allocated Box
3
left.debug_print(depth + 1)
Box automatically dereferences for method calls
4
fn new_branch(value: T, left: TreeNode<T>, right: TreeNode<T>)
Accepts owned TreeNodes, converts to Boxes inside the enum