capypad
0 day streak
rust / intermediate
Snippet

Box<T> for Heap Allocation

Box<T> allocates data on the heap instead of the stack. Use it for recursive data structures (like linked lists) where the compiler needs a known size, or when you want heap allocation semantics. Dereferencing with * gives you the value back.

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
fn main() {
let boxed_number: Box<i32> = Box::new(42);
let unwrapped = *boxed_number;
 
 
println!("Boxed: {}\nUnwrapped: {}", boxed_number, unwrapped);
 
let boxed_slice: Box<[i32]> = Box::new([1, 2, 3, 4, 5]);
println!("Boxed slice length: {}", boxed_slice.len());
 
let mut boxed_vec = Box::new(vec![10, 20, 30]);
boxed_vec.push(40);
println!("Modified vec: {:?}", boxed_vec);
 
let last = boxed_vec.pop();
println!("Popped: {:?}\nVec: {:?}", last, boxed_vec);
 
 
struct Node<T> {
value: T,
next: Option<Box<Node<T>>>,
}
 
let leaf = Node {
value: 42,
next: None,
};
let branch = Node {
value: 1,
next: Some(Box::new(leaf)),
};
println!("Linked node value: {}", branch.value);
}
Breakdown
1
Box::new(42)
Allocates i32 on the heap, returns Box<i32>
2
*boxed_number
Dereferences to get the inner i32 value
3
Box<[i32]>
Box with a slice type; fixed-size array on heap
4
Box::new(vec![...])
Box can also hold dynamically-sized collections
5
Option<Box<Node<T>>>
Recursive type only works with indirection via Box