Skip to content

Vec::clear

Vec methods · Collections

Level: reference · for working programmers

One line: Drop every element, keep the buffer.

pub fn clear(&mut self)

Stable since 1.0.0.

Exactly truncate(0). Length becomes 0, capacity does not change, and every element's destructor runs, front to back.

Keeping the buffer is the point, and it is the reason to prefer this over v = Vec::new(). In a loop that refills the same vector every round, clear allocates once for the whole run; reassigning allocates every round.

That makes clear + refill the standard reused-buffer idiom — for a line buffer, a scratch vector inside a hot loop, a per-frame list.

If you want the memory back too, follow with shrink_to_fit or shrink_to. If you want the elements rather than their destructors, drain(..) hands them to you.

Example

vec_clear.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];
    v.clear();
    println!("{v:?} len {} is_empty {}", v.len(), v.is_empty());

    // It keeps the buffer. That is the reason to prefer it over `v = Vec::new()`
    // when the vector is about to be refilled.
    let mut buf: Vec<u8> = Vec::with_capacity(1024);
    buf.extend_from_slice(&[7; 1024]);
    buf.clear();
    println!("after clear: len {} cap {}", buf.len(), buf.capacity());
    buf.push(1);
    println!("refilled with no allocation: cap still {}", buf.capacity());

    // Reassigning instead throws the buffer away.
    let mut other: Vec<u8> = Vec::with_capacity(1024);
    println!("before reassignment: cap {}", other.capacity());
    other = Vec::new();
    println!("after reassignment:  cap {}", other.capacity());

    // Every element is dropped, front to back.
    struct Noisy(char);
    impl Drop for Noisy {
        fn drop(&mut self) { println!("  dropping {}", self.0); }
    }
    let mut v = vec![Noisy('a'), Noisy('b')];
    println!("clear() on two elements:");
    v.clear();

    // The buffer-reuse loop this enables: one allocation for the whole run.
    let mut line: Vec<u8> = Vec::new();
    let mut caps = vec![];
    for word in ["alpha", "beta", "gamma"] {
        line.clear();
        line.extend_from_slice(word.as_bytes());
        caps.push(line.capacity());
    }
    println!("capacity across three refills: {caps:?}");
}

Verified output of vec_clear.rs — regenerated by tools/run_examples.py, never hand-typed.

[] len 0 is_empty true
after clear: len 0 cap 1024
refilled with no allocation: cap still 1024
before reassignment: cap 1024
after reassignment:  cap 0
clear() on two elements:
  dropping a
  dropping b
capacity across three refills: [8, 8, 8]

See also

Vec::clear in the standard library ↗