I'd like to create an iterator that for this input:
[1, 2, 3, 4]
Will contain the following:
(1, 2)
(2, 3)
(3, 4)
Peekable seems ideal for this, but I'm new to Rust, so this naïve version doesn't work:
fn main() {
let i = ['a', 'b', 'c']
.iter()
.peekable();
let j = i.map(|x| (x, i.peek()));
println!("{:?}", j);
println!("Hello World!");
}
What am I doing wrong?
You can use the
windowsmethod on slices, and then map the arrays into tuples:playground
If you want a solution that works for all iterators (and not just slices) and are willing to use a 3rd-party library you can use the
tuple_windowsmethod from itertools.playground
If you're not willing to use a 3rd-party library it's still simple enough that you can implement it yourself! Here's an example generic implementation that works for any
Iterator<Item = T>whereT: Clone:playground