Vec::truncate¶
Level: reference · for working programmers
One line: Keep the first len elements and drop the rest.
Stable since 1.0.0.
A len greater than or equal to the current length does nothing — it never grows. truncate(0) is clear.
The dropped elements really are dropped, from the back forwards, so destructors run. That is the difference from set_len, which lowers the length without dropping anything and leaks whatever was above it.
Capacity is untouched. This frees no memory; it only shortens the vector. Follow it with shrink_to_fit if the buffer should shrink too.
For "keep the last n" there is no single call — v.drain(..v.len() - n) is the usual spelling, and it needs the empty-vector case thought about first.
Example¶
vec_truncate.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let mut v = vec![1, 2, 3, 4, 5];
v.truncate(2);
println!("{v:?}");
// A len that is >= the current one does nothing. It never grows.
let mut v = vec![1, 2];
v.truncate(10);
println!("truncate(10) on len 2: {v:?}");
// truncate(0) is clear().
let mut v = vec![1, 2, 3];
v.truncate(0);
println!("truncate(0): {v:?} is_empty {}", v.is_empty());
// The dropped elements really are dropped, in order from the back.
struct Noisy(u8);
impl Drop for Noisy {
fn drop(&mut self) { println!(" dropping {}", self.0); }
}
{
let mut v = vec![Noisy(1), Noisy(2), Noisy(3), Noisy(4)];
println!("truncate(1) on four elements:");
v.truncate(1);
println!(" survivor: {}", v[0].0);
} // the survivor drops here, at the end of the block
// Capacity is untouched — this frees no memory.
let mut v: Vec<u8> = Vec::with_capacity(64);
v.extend_from_slice(&[0; 64]);
v.truncate(1);
println!("len {} cap {}", v.len(), v.capacity());
v.shrink_to_fit();
println!("after shrink_to_fit: len {} cap {}", v.len(), v.capacity());
}
Verified output of vec_truncate.rs — regenerated by tools/run_examples.py, never hand-typed.
[1, 2]
truncate(10) on len 2: [1, 2]
truncate(0): [] is_empty true
truncate(1) on four elements:
dropping 2
dropping 3
dropping 4
survivor: 1
dropping 1
len 1 cap 64
after shrink_to_fit: len 1 cap 1
See also¶
Vec::clear—truncate(0), spelled so it readsVec::resize— the version that can also growVec::set_len— the unsafe one that drops nothingVec::drain— removing a range and keeping the elements