Shrink Capacity With into_boxed_slice

Drop a Vec capacity down to its length with into_boxed_slice, then convert back with into_vec and note the capacity now equals the element count.

RustData Integrity

Code

rustsnippet
17 lines
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());
}

What the code does

Under the hood: the function main.

Caveats

  • Copy, run: the standard library answers every call in the file.

Applying it

Entry signature: fn main()

Look for the vec len=, boxed len=, sum= prefixes when the file runs; they tie each line to its step.

Statements that matter

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

Interactive Tools for This Topic

FAQ

What does Shrink Capacity With into_boxed_slice print when run?
The script runs standalone; its 4 labeled outputs include `vec len=`, `boxed len=`, `sum=`.