实现说明
Box 把大缓冲搬上堆可以归结为函数 main。
使用要点
- 跑完文件,输出里会留下标记——
stack array bytes:、boxed len:、box variable bytes:。
常见问题
运行「Box 把大缓冲搬上堆」会打印什么?
整个文件跑完,输出行以 stack array bytes:、boxed len:、box variable bytes: 这类前缀开头。
核心语句
let on_heap = Box::new([0u8; 1024 * 1024]);
let on_stack = [0u8; 1024];
代码示例
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]);
}