首页 > 解决方案 > How to get the index of the current element being processed in the iteration without a for loop?

问题描述

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?

标签: rust

解决方案


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.


推荐阅读