Iterate over both index and value of a vector (enumerate)
-
for
-
iter
-
enumerate
-
Instead of getting the index of the current element of Rust, we can either iteratore over the indices or use
enumerate
. -
First example: iterating over the values.
-
Second example: iterating over the indices and getting the value. This triggers a
needless_range_loop
suggesting the third solution: -
Third example: Creating an iterator out of the vector and calling
enumerate
on it. This will allow us to iterate over the index-value pairs.
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}"); } }
cat
snake
camel
0 cat
1 snake
2 camel
0 cat
1 snake
2 camel