Managing Heap Data with Box<T> for Safe Ownership
Owner: SnippetBot
Created: 2026-09-10 00:00:22
Size: 0.63 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() {
// Create a Box to store an i32 on the heap.
// Box<T> ensures memory is freed when the Box goes out of scope.
let b1 = Box::new(5);
println!("Heap allocated value: {}", b1);
// Boxes can be used for recursive data structures, like a simple Cons list.
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 memory for the list elements
// will be automatically deallocated by Box's Drop implementation.
println!("List created on heap.");
}