How to destructure a slice in an Iterator?

For example, we have a Vec<T> and we need to iterate over chunks. If the .chunks() method would've returned a collection of tuples we would simply use smth like this:

let vec = Vec::new();
vec.chunks(2).into_iter().for_each(|(a, b)| println!("{} {}", a, b));

But it returns a collection of slices, so this syntax doesn't work.

There's itertools::tuples that's implemented for tuples up to arity 4 (as currently Rust doesn't have a way to abstract over tuples of arbitrary arity). Also, there's the unstable std method array_chunks that works for chunks of arbitrary size thanks to const generics; you can destructure arrays as they have a constant size.

1 Like

Thanks. .tuples is nice.

let vec = Vec::new();
vec.iter().tuples().for_each(|(a, b)| println!("{} {}", a, b));

Note that there is a slice pattern syntax:

match slice {
    [a, b, .., c] => {}
    // ...
}

However, since Rust doesn't statically know the size of slices returned by chunks, you can't destructure the slice in the closure arguments. You would need to do an explicit match (or if let) with a panic in the else branch.

1 Like