How to iterate a Vec<T> with the indexed position?
I need to iterate a Vec
including the position for each iterated element. I'm sure this is already in the API but I cannot see it.
I need something like this:
fn main() {
let v = vec![1; 10];
for (pos, e) in v.iter() {
// do something here
}
}
You can use the Iterator::enumerate
method:
fn main() {
let v = vec![1; 10];
for (pos, e) in v.iter().enumerate() {
println!("Element at position {}: {:?}", pos, e);
}
}
Playground