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