Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index of the current element being processed in the iteration without a for loop?

Tags:

rust

I have read How to iterate a Vec<T> with the indexed position? where the answer is to use enumerate in a for-loop.

But if I don't use a for-loop like this:

fn main() {
    let v = vec![1; 10]
        .iter()
        .map(|&x| x + 1  /* + index */ ) // <--
        .collect::<Vec<_>>();

    print!("v{:?}", v);
}

How could I get the index in the above closure?

like image 220
Tom Avatar asked Nov 06 '19 19:11

Tom


2 Answers

You can also use enumerate!

let v = vec![1; 10]
    .iter()
    .enumerate()
    .map(|(i, &x)| x + i)
    .collect::<Vec<_>>();

println!("v{:?}", v);   // prints v[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's see how this works. Iterator::enumerate returns Enumerate<Self>. That type also implements Iterator:

impl<I> Iterator for Enumerate<I>
where
    I: Iterator,
{
    type Item = (usize, <I as Iterator>::Item);
    // ...
}

As you can see, the new iterator yields tuples of the index and the original value.

like image 196
Lukas Kalbertodt Avatar answered Nov 15 '22 11:11

Lukas Kalbertodt


You can simply use enumerate:

fn main() {
    let v = vec![1; 10]
        .iter()
        .enumerate()
        .map(|(i, x)| i + x)
        .collect::<Vec<_>>();

    print!("v{:?}", v);
}

The reason for this is because the for loop takes an enumerator: In slightly more abstract terms:

for var in expression {
    code
}

The expression is an iterator.

like image 20
Tom Avatar answered Nov 15 '22 10:11

Tom