How to enumerate

Use the `.enumerate()` method on any iterator to get a new iterator yielding pairs of `(index, item)`, starting the index at 0 by default.

Use the .enumerate() method on any iterator to get a new iterator yielding pairs of (index, item), starting the index at 0 by default. This is the standard, idiomatic way to access both the position and the value of elements while iterating in Rust.

Here is a basic example iterating over a vector of strings:

let fruits = vec!["apple", "banana", "cherry"];

for (index, fruit) in fruits.iter().enumerate() {
    println!("{}: {}", index, fruit);
}
// Output:
// 0: apple
// 1: banana
// 2: cherry

If you need to start the index from a number other than 0, chain .zip() with a range iterator. This is cleaner than manually managing a counter variable.

let fruits = vec!["apple", "banana", "cherry"];
let start_index = 10;

for (index, fruit) in fruits.iter().zip(start_index..) {
    println!("Item {}: {}", index, fruit);
}
// Output:
// Item 10: apple
// Item 11: banana
// Item 12: cherry

You can also use enumerate() with filter_map or map to transform data based on position. For instance, to create a vector of indices where the element is "banana":

let fruits = vec!["apple", "banana", "cherry", "banana"];

let banana_indices: Vec<usize> = fruits
    .iter()
    .enumerate()
    .filter_map(|(i, &f)| if f == "banana" { Some(i) } else { None })
    .collect();

println!("{:?}", banana_indices); // Output: [1, 3]

Remember that enumerate() returns an iterator, so it doesn't consume the original collection unless you collect it or iterate to completion. It works with any type that implements IntoIterator, including slices, vectors, and other iterators.