std-method

slice::chunk_by

Group consecutive elements while the predicate accepts each adjacent pair. Equal elements separated by different values do not become a single group. Expected stdout (not executed): [1, 1] [2, 2] [1] Common mistake: Expecting global grouping of equal values.

Formal Syntax & Structure

rust syntaxrust
slice.chunk_by(|left, right| condition)

Working Example

Example Snippetrust
fn main() {    let data = [1, 1, 2, 2, 1];    for run in data.chunk_by(|a, b| a == b) { println!("{run:?}"); }}
Rust Reference