Unexpected iterator behavior?

Hello

I am surprised by the difference between the two following iterators.
Why is the second iterator not reversed? Is this expected behavior?

fn main() {
    let v = vec![4,8,15,16,23,42];
    println!("First");
    for (i, e) in v.iter().enumerate().rev() {
        println!("{};{}", i, e);
    }
    println!("Second");
    for (i, e) in v.iter().rev().enumerate() {
        println!("{};{}", i, e);
    }
}

(Playground)

Output:

First
5;42
4;23
3;16
2;15
1;8
0;4
Second
0;42
1;23
2;16
3;15
4;8
5;4

It’s expected behavior. In the second example, the enumeration is not reversed, because you didn’t call .rev() on the iterator returned by .enumerate().

It feels counter intuitive but ok. Thank you

To break down a bit what happens:

First case:
v.iter() would return:
4, 8, 15, 16, 23, 42
enumerate() adds indexes on this sequence:
(0, 4), (1, 8), (2, 15), (3, 16), (4, 23), (5, 42)
Finally, rev() reverts this sequence into:
(5, 42), (4, 23), (3, 16), (2, 15), (1, 8), (0, 4)

Second case:
v.iter() would return:
4, 8, 15, 16, 23, 42
rev() reverts this sequence into:
42, 23, 16, 15, 8, 4
Finally, enumerate() add indexes to the elements of the sequence:
(0, 42), (1, 23), (2, 16), (3, 15), (4, 8), (5, 4)

7 Likes