Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. Iterator::enumerate() / zip() / flat_map()

Iterator::enumerate() / zip() / flat_map()

Rust iterators include enumerate() for indexed iteration, zip() for combining two iterators, and flat_map() for transforming and flattening nested iterators.

Syntax

// enumerate(): Returns tuples of (index, element).
for (i, val) in vec!["a", "b", "c"].iter().enumerate() {
    println!("{}: {}", i, val);
}

// zip(): Combines two iterators into an iterator of tuples.
let keys = vec!["a", "b", "c"];
let vals = vec![1, 2, 3];
let pairs: Vec<(_, _)> = keys.iter().zip(vals.iter()).collect();

// flat_map(): Transforms each element and flattens the result.
let words = vec!["hello world", "foo bar"];
let chars: Vec<&str> = words.iter().flat_map(|s| s.split_whitespace()).collect();

// flatten(): Flattens a nested iterator by one level.
let nested = vec![vec![1, 2], vec![3, 4], vec![5]];
let flat: Vec<i32> = nested.into_iter().flatten().collect();

Method List

MethodDescription
iter.enumerate()Returns an iterator that yields (index, value) tuples.
iter.zip(other)Combines two iterators into an iterator of (a, b) tuples.
iter.flat_map(|x| ...)Transforms each element and flattens the resulting iterators.
iter.flatten()Flattens a nested iterator by one level.
iter.chain(other)Concatenates two iterators into a single iterator.
iter.take(n)Takes only the first n elements from the iterator.
iter.skip(n)Skips the first n elements of the iterator.
iter.step_by(n)Takes every nth element from the iterator.
iter.rev()Returns an iterator in reverse order (requires DoubleEndedIterator).
iter.peekable()Returns an iterator that allows peeking at the next element without consuming it.

Sample Code

fn main() {
    // enumerate(): Loops with an index.
    let fruits = vec!["apple", "banana", "cherry"];
    for (i, fruit) in fruits.iter().enumerate() {
        println!("{}: {}", i, fruit);
    }

    // Build a numbered list with enumerate().
    let numbered: Vec<String> = fruits.iter()
        .enumerate()
        .map(|(i, f)| format!("{}. {}", i + 1, f))
        .collect();
    println!("numbered: {:?}", numbered);

    // zip(): Combines two Vecs together.
    let names = vec!["Alice", "Bob", "Carol"];
    let scores = vec![90, 85, 92];
    let combined: Vec<(_, _)> = names.iter().zip(scores.iter()).collect();
    println!("zip: {:?}", combined);

    // Build a HashMap with zip().
    use std::collections::HashMap;
    let map: HashMap<_, _> = names.iter().zip(scores.iter()).collect();
    println!("zip to HashMap: {:?}", map);

    // flat_map(): Splits each string into words and flattens the result.
    let sentences = vec!["hello world", "foo bar baz"];
    let words: Vec<&str> = sentences.iter().flat_map(|s| s.split_whitespace()).collect();
    println!("flat_map words: {:?}", words);

    // flatten(): Flattens a nested Vec.
    let nested = vec![vec![1, 2, 3], vec![4, 5], vec![6]];
    let flat: Vec<i32> = nested.into_iter().flatten().collect();
    println!("flatten: {:?}", flat);

    // chain(): Concatenates two iterators.
    let a = vec![1, 2, 3];
    let b = vec![4, 5, 6];
    let chained: Vec<i32> = a.iter().chain(b.iter()).copied().collect();
    println!("chain: {:?}", chained);

    // take() and skip().
    let v: Vec<i32> = (1..=10).collect();
    let first3: Vec<_> = v.iter().take(3).collect();
    let skip3: Vec<_> = v.iter().skip(3).collect();
    println!("take(3): {:?}", first3);
    println!("skip(3): {:?}", skip3);
}

Output

0: apple
1: banana
2: cherry
numbered: ["1. apple", "2. banana", "3. cherry"]
zip: [("Alice", 90), ("Bob", 85), ("Carol", 92)]
zip to HashMap: {"Alice": 90, "Bob": 85, "Carol": 92}
flat_map words: ["hello", "world", "foo", "bar", "baz"]
flatten: [1, 2, 3, 4, 5, 6]
chain: [1, 2, 3, 4, 5, 6]
take(3): [1, 2, 3]
skip(3): [4, 5, 6, 7, 8, 9, 10]

Notes

zip() stops when the shorter iterator is exhausted, so mismatched lengths are handled safely. If you need to process all elements from both iterators, use zip_longest() from the itertools crate.

flat_map() is equivalent to map().flatten(). It is also useful for handling nested Option or Result values — for example, iter.flat_map(|x| x.ok()) discards errors and keeps only the successful values.

For transforming and filtering, see Iterator::map() / filter().

If you find any errors or copyright issues, please .