RRust By Example
intermediateIterators

Iterator Enumerate

Get index and value with enumerate.

Iterator Enumerate

Get index and value with enumerate.

Difficulty

Intermediate

Code

rust
fn main() {
    let fruits = vec!["apple", "banana", "cherry"];

    for (i, fruit) in fruits.iter().enumerate() {
        println!("{}. {}", i + 1, fruit);
    }

    // find with index
    let nums = vec![10, 20, 30, 40, 50];
    let found = nums.iter().enumerate().find(|(_, &v)| v > 25);
    println!("first > 25: {:?}", found);

    // collect into indexed map
    let indexed: Vec<(usize, &str)> = fruits.into_iter().enumerate().collect();
    println!("indexed: {:?}", indexed);
}

Explanation

enumerate() yields (index, value) pairs.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the iterators category to build a complete understanding of this topic.

More Iterators Examples