capypad
0 day streak
rust / beginner
Snippet

Box<T> for Heap Allocation

Box<T> allocates a value on the heap instead of the stack. It's useful when you need a known-sized container with stable size, or when recursion requires an indirection. Box::new() creates the box and places the value inside. Dereferencing with * accesses the contained value. Boxes implement Deref and Drop automatically, making them feel like regular references but with owned heap storage.

snippet.rs
rust
1
fn main() {\n let boxed: Box<i32> = Box::new(42);\n let value = *boxed;\n \n println!("Boxed value: {}, dereferenced: {}", boxed, value);\n \n let point = Box::new((0, 0));\n println!("Point: ({}, {})", point.0, point.1);\n \n let mut boxed_slice = Box::new([1, 2, 3, 4, 5]);\n boxed_slice[0] = 10;\n println!("Modified slice: {:?}", boxed_slice);\n}
Breakdown
1
Box<i32>
Type annotation for a box containing an i32 on the heap
2
Box::new(42)
Creates a box and heap-allocates the value 42
3
*boxed
Dereference operator extracts the value from the box
4
Box::new((0, 0))
Box can contain any type, including tuples
5
boxed_slice[0] = 10
Box<T> where T is an array allows mutable indexing
6
println!("...{:?}", boxed_slice)
:? debug formatting prints array contents