231. slice::chunk_by — Group Consecutive Elements Without the Index Bookkeeping
Splitting a slice into runs of equal (or related) elements usually means a manual loop with a start index and an off-by-one waiting to happen. slice::chunk_by does it in one call.
You want to break [1, 1, 2, 3, 3, 3, 1] into its runs of equal values. The hand-rolled version tracks where each run starts and has to remember to flush the last one:
| |
chunk_by takes a predicate over consecutive pairs and starts a new chunk whenever it returns false:
| |
The predicate is any relation between neighbours, not just equality. Want the ascending runs of a sequence? Split where the order breaks:
| |
Each chunk is a borrowed &[T] into the original slice — no copying. There’s a chunk_by_mut for when you need &mut [T] slices instead. (Stable since Rust 1.77; it was briefly named group_by.)