How to skip a number in iter.enumerate()

I have two iterators that I want to chain. That's easy: left.chain(right). But I also would like to get the index. Still easy: left.chain(right).enumerate(). Except that I would like to skip a number when going from left to right. How can I do it?

I want to be able to do:

let left = ['a', 'b', 'c'].iter();
let right = ['e', 'f'].iter();
assert_eq!(
    left.chain_enumerate_and_skip_one(right).collect(),
    vec![(0, 'a'), (1, 'b'), (2, 'c'), /* not 3 */ (4, 'd'), (5, 'e')]);

How about this?


fn main() {
    let left = ['a', 'b', 'c'].iter();
    let right = ['e', 'f'].iter();
    let n = left.len() + 1;
    
    let iter_output: Vec<_> = left.enumerate()
        .chain(right.enumerate().map(|(i,x)| (i+n,x)))
        .map(|(i,x)| (i,*x))
        .collect();
    
    assert_eq!(
        iter_output,
        vec![(0, 'a'), (1, 'b'), (2, 'c'), /* not 3 */ (4, 'e'), (5, 'f')]);
}
1 Like