238. slice::chunks_exact_mut — Edit a Slice in Fixed-Size Blocks Without Index Math
Processing a buffer N elements at a time usually means a while i + N <= len loop and a pile of buf[i..i+N] slicing. chunks_exact_mut hands you each fixed-size block as a &mut [T] — no index bookkeeping, no off-by-one.
The manual-window loop
| |
It works, but every one of i + 2, <= len, and i += 2 is a place to get the bounds wrong.
chunks_exact_mut yields the blocks for you
| |
Each pair is a &mut [T; 2]-shaped slice you can mutate in place. The iterator stops once fewer than 2 elements remain, so you never index past the end.
The “exact” part: a leftover tail is skipped, not sliced
Unlike chunks_mut, the last partial block is not yielded — that guarantee is exactly why the block size is reliable:
| |
Reach for the remainder through by_ref() + into_remainder(): iterate the full blocks, then claim whatever fell short. If you drop the loop’s by_ref(), the iterator is moved and into_remainder is unavailable.
Why not just chunks_mut?
chunks_mut(n) also walks a slice in steps of n, but its final chunk can be shorter than n, so any code assuming a fixed width needs a length check every iteration. chunks_exact_mut trades that partial tail for a compile-time-friendly promise that every yielded block is exactly n long — which also lets the optimizer generate tighter code. There’s a read-only chunks_exact for &[T], and as_chunks_mut if you want real &mut [T; N] arrays instead of slices.