← 中文资源

简体中文版本

用 into_boxed_slice 裁掉多余容量

into_boxed_slice 把 Vec 的容量裁到元素个数,转成定长切片后无法再 push;用 into_vec 零拷贝转回 Vec 时,容量也随之等于长度。

阅读英文原文

实现说明

用 into_boxed_slice 裁掉多余容量可以归结为函数 main。

使用要点

  • 跑完文件,输出里会留下标记——vec len=、boxed len=、sum=。

常见问题

运行「用 into_boxed_slice 裁掉多余容量」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 vec len=、boxed len=、sum= 这类标签。

核心语句

let total: u32 = boxed.iter().sum();
let boxed: Box<[u32]> = queue.into_boxed_slice();

代码示例

fn main() {
    // 预留 16 个位置,实际只放三个
    let mut queue: Vec<u32> = Vec::with_capacity(16);
    queue.extend([10, 20, 30]);
    println!("vec len={} cap={}", queue.len(), queue.capacity());

    // into_boxed_slice:容量裁到元素个数,此后不能再 push
    let boxed: Box<[u32]> = queue.into_boxed_slice();
    println!("boxed len={} bytes={}", boxed.len(), std::mem::size_of_val(&*boxed));

    let total: u32 = boxed.iter().sum();
    println!("sum={} first={:?} last={:?}", total, boxed.first(), boxed.last());

    // 反向转换零拷贝:变回 Vec 后容量等于长度
    let back: Vec<u32> = boxed.into_vec();
    println!("back len={} cap={}", back.len(), back.capacity());
}