How to iterate a Vec with the indexed position?

2019-06-16 21:02发布

I need to iterate a Vec but I need 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 
    }
}

标签: rust
1条回答
何必那么认真
2楼-- · 2019-06-16 21:51

You can use the enumerate() function:

fn main() {
    let v = vec![1;10];
    for (pos, e) in v.iter().enumerate() {
        println!("Element at position {}: {:?}", pos, e);
    }
}

Playpen

查看更多
登录 后发表回答