#212 Jun 19, 2026

212. slice::fill / fill_with — Reset Every Element Without the Loop

Clearing a buffer with a hand-rolled for loop is noise. slice::fill overwrites every element in one call — and fill_with builds a fresh value per slot.

You’ve got a buffer to reset between iterations, so the reflex is to write the loop:

1
2
3
for x in buf.iter_mut() {
    *x = 0;
}

fill says the same thing in one line, and it pairs perfectly with the reuse-a-buffer trick: keep the allocation, wipe the contents.

1
2
3
let mut buf = vec![7, 7, 7, 7];
buf.fill(0);
assert_eq!(buf, [0, 0, 0, 0]);

It works on any &mut [T] where T: Clone, so array and slice subranges are in too:

1
2
3
let mut grid = [[1u8; 3]; 2];
grid[0].fill(9);
assert_eq!(grid[0], [9, 9, 9]);

The catch: fill clones one value into every slot. When you need a distinct value per element — a counter, a random number, a fresh allocation — reach for fill_with, which calls the closure once per slot:

1
2
3
4
5
6
7
let mut ids = [0u32; 4];
let mut next = 0;
ids.fill_with(|| {
    next += 1;
    next
});
assert_eq!(ids, [1, 2, 3, 4]);

Use fill(value) when every slot is the same, and fill_with(|| ...) when each slot earns its own. Either way: no index, no loop, no off-by-one.

← Previous 211. Iterator::inspect — Debug a Lazy Chain Without Tearing It Apart Next → 213. abs_diff — The Gap Between Two Numbers, No Underflow, No Overflow