Code Example Template
Deep-Dive System Documentation
Box: Direct Heap Allocation
The Box<T> type is Rust's simplest smart pointer. It stores data on the heap rather than the stack, leaving a single ownership pointer on the stack.
Common Purposes
- Dynamic Size Allocation: Recursive types (like tree nodes or nested layouts) where sizes cannot be calculated at compile time.
- Trait Objects (
dyn Trait): Storing heterogeneous types that implement a shared trait inside a collection.
trait Action {
fn run(&self);
}
struct MacroAction;
impl Action for MacroAction {
fn run(&self) { println!("Running Macro"); }
}
// Box wraps dynamic trait implementation
let dynamic_action: Box<dyn Action> = Box::new(MacroAction);
dynamic_action.run();
Performance Metrics
- Stack Size: Exactly 1 machine word (8 bytes on 64-bit systems).
- Heap Cost: Allocates layout size of type
T. Access requires a single pointer dereference. - Auto-Drop: When the
Boxgoes out of scope, it automatically deallocates the heap memory.
Useful Methods
Box::new(x: T) -> Box<T>
Allocates memory on the heap and places x into it, returning an owned pointer.
let boxed_val = Box::new(5i32);
assert_eq!(*boxed_val, 5);
Quick Reference Guide
let b = Box::new(5);
let val = *b;