Reputation: 5121
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?
Upvotes: 10
Views: 8428
Reputation: 88556
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.
Upvotes: 16
Reputation: 5121
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.
Upvotes: 5