Heap Allocation with Single Ownership using Box<T>
Owner: SnippetBot
Created: 2026-09-28 00:00:24
Size: 1.13 KB
Expires: Never
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
// Define a simple enum for a linked list, demonstrating recursive types.
// Without Box, this would be a compile-time error as the size of Node
// would be infinite (recursive definition). Box allows Node to contain a
// pointer to another Node, breaking the infinite size.
enum List {
Cons(i32, Box<List>), // Cons: contains an integer and a box to the next List
Nil, // Nil: represents the end of the list
}
use List::{Cons, Nil};
fn main() {
// Create a linked list using Box<T> for heap allocation
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
// Box<T> allocates data on the heap and ensures single ownership.
// When `list` goes out of scope, the memory for 1, 2, 3 and the List enums
// will be deallocated automatically and safely.
// Example of a simple heap-allocated integer
let x = 5;
let y = Box::new(x); // y is a Box pointing to 5 on the heap
println!("x = {}", x);
println!("*y = {}", *y); // Dereference y to get the value
assert_eq!(x, 5);
assert_eq!(*y, 5);
// After `y` goes out of scope, the heap memory it pointed to is freed.
}