How to iterate a Vec<T> with the indexed position?

For LoopRustIterator

For 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);
    }
}

Playground

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbitlonerView Question on Stackoverflow
Solution 1 - For Loopuser4316209View Answer on Stackoverflow