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:
| |
fill says the same thing in one line, and it pairs perfectly with the reuse-a-buffer trick: keep the allocation, wipe the contents.
| |
It works on any &mut [T] where T: Clone, so array and slice subranges are in too:
| |
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:
| |
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.