Search code examples
rustiteratorenumerate

iterator that skips, steps by and returns correct index


I am writing a program which needs an iterator which starts at the nth value in an array and steps by m giving the correct index (n + xm) of the element. Currently my code:

fn main() {
    let mut test = [false; 10];

    for (index, val) in test.iter_mut().skip(3).step_by(2).enumerate() {
        *val = true;
        println!("{index} = true")
    }

    println!("{:?}", test)
}

// -> 
// 0 = true
// 1 = true
// 2 = true
// 3 = true
// [false, false, false, true, false, true, false, true, false, true]

gives the correct element (val) but the wrong index (index). For example the first line of output should be 3 = true. Could you please let me know how to get the correct index's?

Thanks,


Solution

  • TL;DR: Enumerate before skipping.

    Operations on iterators (instances that implement Iterator) are sequential. They work lazily, by applying another type that calls inner’s next and then performs it’s own operation. What I’m trying to tell is that order of operations matters. With this knowledge you now can just put enumeration to the beginning of this operation pipe:

    test.iter_mut()
        .enumerate()
        .skip(3)
        .step_by(2)
        .for_each(|(index, val)| {
            *val = true;
            println!("{index} = true");
        });