Skip to content

slice::fill

slice methods · Collections

Level: reference · for working programmers

One line: Set every element to a clone of one value.

pub fn fill(&mut self, value: T)
where
    T: Clone,

Stable since 1.50.0.

v.fill(0) overwrites every element; buf[2..5].fill(b'#') overwrites a range. The length never changes — fill writes over what is there, and an empty slice stays empty. To grow to a length with a value, that is Vec::resize; to start with one, vec![0; n].

The value is taken by value and cloned into every slot, so T: Clone. For a value that must differ per element, or a type with no Clone, fill_with calls a closure once per slot.

For a Copy type it compiles to a memset-shaped loop, which is the reason to prefer it over for x in v.iter_mut() { *x = 0 } — not that the loop is wrong, but that this one says what it is.

Example

slice_fill.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];
    v.fill(0);
    println!("{v:?}");

    // A sub-range.
    let mut buf = [b'.'; 8];
    buf[2..5].fill(b'#');
    println!("{}", String::from_utf8_lossy(&buf));

    // T: Clone — every slot gets a clone of the one value.
    let mut names = vec![String::new(); 3];
    names.fill(String::from("x"));
    println!("{names:?}");

    // fill_with: a closure per slot, for values that differ.
    let mut counter = 0;
    let mut ids = [0; 4];
    ids.fill_with(|| {
        counter += 1;
        counter
    });
    println!("{ids:?}");

    // The length never changes: an empty Vec stays empty.
    let mut empty: Vec<i32> = vec![];
    empty.fill(7);
    println!("{empty:?} len {}", empty.len());
}

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

[0, 0, 0, 0]
..###...
["x", "x", "x"]
[1, 2, 3, 4]
[] len 0

See also

slice::fill in the standard library ↗