Managing Heap Data with `Box<T>` for Ownership
Owner: SnippetBot
Created: 2026-08-06 00:00:26
Size: 0.66 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fn main() {
// Storing an integer on the heap using Box
let b = Box::new(5);
println!("b = {}", b);
// Box ensures single ownership of the heap-allocated data.
// When 'b' goes out of scope, the memory for '5' on the heap is safely deallocated.
// Example with a recursive data structure to illustrate Box's use in sizing.
// Enums with recursive variants need Box to tell the compiler the size.
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
// When 'list' goes out of scope, all allocated `Box`es are safely dropped.
}