Iterate over both index and value of a vector (enumerate)

vec! iter enumerate needless_range_loop

In most cases when when want to process each value in a vector we don't car about the actual location of the value. We just iterate over the values and do something with them. E.g. print them. This is what we see in the first example.

There are, however cases when we also need to know the location of each value. There are two approaches we can use.

We can iterate over the numbers from 0 till the number of elements in the vector. These will be the indices. Then using the current number we can access the respective value in the vector. This is the second example. This code triggers a needless_range_loop violation suggesting the third solution

We can create an iterator out of the vector using iter and calling enumerate on it. This will allow us to iterate over the index-value pairs.

Code

examples/enumerate/src/main.rs

fn main() {
    let animals = vec!["cat", "snake", "camel"];
    for animal in &animals {
        println!("{animal}");
    }
    println!();

    #[allow(clippy::needless_range_loop)]
    for ix in 0..animals.len() {
        println!("{ix} {}", animals[ix]);
    }
    println!();

    for (ix, animal) in animals.iter().enumerate() {
        println!("{ix} {animal}");
    }
}

Output

cat
snake
camel

0 cat
1 snake
2 camel

0 cat
1 snake
2 camel

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo