50. slice::chunk_by — Group Consecutive Elements
Need to split a slice into groups of consecutive elements that share a property? chunk_by does exactly that — no allocations, no manual index tracking.
The problem
Imagine you have a sorted list of temperatures and want to group them into runs of non-decreasing values. Without chunk_by, you’d write a loop tracking where each group starts and ends:
| |
Enter chunk_by
Stabilized in Rust 1.77, slice::chunk_by splits a slice between consecutive elements where the predicate returns false. Each chunk is a sub-slice where every adjacent pair satisfies the predicate:
| |
The predicate |a, b| a <= b keeps elements in the same chunk as long as values are non-decreasing. The moment a value drops, a new chunk begins.
Group by equality
A common use case is grouping runs of equal elements:
| |
Notice this groups consecutive equal elements — it’s not the same as a GROUP BY in SQL. The two runs of 2 stay separate because they aren’t adjacent.
Mutable chunks
There’s also chunk_by_mut if you need to modify elements within each group:
| |
Key details
- Zero-cost: returns sub-slices of the original data — no allocations
- Predicate sees pairs:
|a, b|receives each consecutive pair; a new chunk starts where it returnsfalse - Works on any slice:
&[T],&mut [T],Vec<T>(via deref) - Stable since Rust 1.77
Next time you reach for a manual loop to group consecutive elements, try chunk_by instead.