How to iterate a Vec<T> with the indexed position?
For LoopRustIteratorFor Loop Problem Overview
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
}
}
For Loop Solutions
Solution 1 - For Loop
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);
}
}