In python I can write the following to iterate by tuples.
it = iter(range(10))
zip(it, it) # [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
Rust wouldn't let me borrow iterator twice (or use same iterator twice because of the move).
let mut i1 = a.iter();
let i2 = &mut i1;
i1.zip(i2).for_each(|(a, b)| println!("a: {}, b: {}", a, b));
I know about itertools crate, I just wonder if there's some hack that would allow me to get by without it if I only need this functionality.
Obviously you can do something like that.
struct Chunks<I: Iterator<Item = T, T> {
seq: I,
}
impl<I: Iterator<Item = T>, T> Iterator for Chunks<I, T> {
type Item = (T, T);
fn next(&mut self) -> Option<Self::Item> {
self.seq.next().zip(self.seq.next())
}
}
But that works only for tuples and not for triples. Triples would require some kind of macroses.
With std::iter::from_fn
you can create one-liner (thanks to @user4815162342).
let mut seq = a.iter();
let chunks = std::iter::from_fn(move || seq.next().zip(seq.next()));
chunks.for_each(|(a, b)| println!("a: {}, b: {}", a, b));