Box Moves Large Buffers To The Heap
Box moves a large buffer off the stack: the array lives on the heap while the binding itself stays one machine word.
Code
use std::mem::size_of_val;
fn main() {
// a small array fits the stack, and size_of_val reports its bytes
let on_stack = [0u8; 1024];
println!("stack array bytes: {}", size_of_val(&on_stack));
// Box moves the same buffer to the heap; the binding is one pointer
let on_heap = Box::new([0u8; 1024 * 1024]);
println!("boxed len: {}", on_heap.len());
println!("box variable bytes: {}", size_of_val(&on_heap));
println!("first/last: {} / {}", on_heap[0], on_heap[on_heap.len() - 1]);
}How it works
Under the hood: the function main.
Points of care
- The toolchain already provides everything it needs in order to run.
Using it
The signature you will reach for first is fn main()
Watch for labeled lines in the run — stack array bytes:, boxed len:, box variable bytes: — when the file runs.
The key statements, annotated
let on_heap = Box::new([0u8; 1024 * 1024]);
let on_stack = [0u8; 1024];
Interactive Tools for This Topic
Box Shadow GeneratorBuild CSS box-shadow values with offset, blur, spread, color, opacity, and inset controls, with a live preview of the result.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Box Moves Large Buffers To The Heap print when run?
- No setup needed: run the file and look for labeled lines like `stack array bytes:`, `boxed len:`, `box variable bytes:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.