Truncate And Clear Keep Capacity

Cut length with truncate or empty a Vec with clear, while capacity stays reserved — reuse the allocation for the next batch instead of reallocating.

RustData Integrity

Code

snippet
fn main() {
    let mut batch: Vec<u32> = (0..100).collect();
    println!("len {} cap {}", batch.len(), batch.capacity());

    // truncate:只裁长度,丢弃 50 之后的元素,容量不变
    batch.truncate(50);
    println!("truncated: len {} cap {}", batch.len(), batch.capacity());

    // clear:清空内容,容量仍然保留,可直接复用
    batch.clear();
    println!("cleared: len {} cap {}", batch.len(), batch.capacity());

    // 复用同一块缓冲:push 重新填充,不再分配
    batch.extend(0..10);
    println!("reused: len {} cap {}", batch.len(), batch.capacity());

    // 需要真正归还内存时才调用 shrink_to_fit
    batch.shrink_to_fit();
    println!("shrunk: len {} cap {}", batch.len(), batch.capacity());
}

How the snippet works

Truncate And Clear Keep Capacity comes down to the function main.

Applying it

The demo output is labeled (len, truncated: len, cleared: len), so every printed line maps back to its originating operation.

Statements that matter

let mut batch: Vec<u32> = (0..100).collect();

Interactive Tools for This Topic

FAQ

What does Truncate And Clear Keep Capacity print when run?
No setup needed: run the file and look for labeled lines like `len`, `truncated: len`, `cleared: len` in the output.