rust / intermediate
Snippet
Box<T> for Heap Allocation and Smart Pointers
Box<T> allocates values on the heap instead of the stack. It's the primary way to create singly-linked data structures like trees and linked lists in Rust. Box<T> implements the Deref trait, so you can use it like a regular reference. The Box is dropped when it goes out of scope, automatically deallocating the heap memory. Box<[T]> creates a dynamically-sized slice reference with known length.
snippet.rs
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
use std::mem;fn main() {let stack_val: i32 = 42;let boxed_val: Box<i32> = Box::new(123);println!("Stack value: {}", stack_val);println!("Boxed value: {}", boxed_val);let boxed_slice: Box<[i32]> = Box::new([1, 2, 3, 4, 5]);println!("Boxed slice len: {}", boxed_slice.len());let mut tree: Option<Box<TreeNode>> = Some(Box::new(TreeNode {value: 1,left: Some(Box::new(TreeNode { value: 2, left: None, right: None })),right: Some(Box::new(TreeNode { value: 3, left: None, right: None })),}));if let Some(ref mut node) = tree {node.value += 10;println!("Root value after modification: {}", node.value);}let size_of_box = mem::size_of::<Box<i32>>();let size_of_i32 = mem::size_of::<i32>();println!("Box<i32> size: {} bytes, i32 size: {} bytes", size_of_box, size_of_i32);}struct TreeNode {value: i32,left: Option<Box<TreeNode>>,right: Option<Box<TreeNode>>,}
Breakdown
1
Box::new(123)
Allocates integer 123 on heap, returns Box<i32>
2
Box<[i32]>
Fat pointer containing pointer and length for heap-allocated slice
3
Option<Box<TreeNode>>
Optional boxed recursive type for tree structure
4
Some(Box::new(TreeNode { ... }))
Constructing tree with boxed child nodes
5
if let Some(ref mut node) = tree { ... }
Pattern matching to borrow boxed content mutably
6
mem::size_of::<Box<i32>>()
Box pointer size (8 bytes on 64-bit) vs actual data size