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.
Code
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
Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.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.String TruncatorTruncate text to a maximum number of characters or words and append a suffix such as an ellipsis, keeping previews and labels within a strict length.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.