typestar

enumerate and zip in Rust

Pairing iterator items with indexes or each other.

fn main() {
    let words = ["ada", "grace", "kay"];

    for (i, word) in words.iter().enumerate() {
        println!("{i}: {word}");
    }

    let ids = [1, 2, 3];
    let paired: Vec<(i32, &str)> =
        ids.iter().copied().zip(words).collect();
    println!("{}", paired.len());
}

How it works

  1. enumerate yields (index, item) pairs.
  2. zip walks two iterators together.
  3. collect builds a Vec of the pairs.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
247
Tokens
104
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 66 seconds.

Type this snippet

Step 2 of 5 in Adapters, step 2 of 14 in Iterators & closures.

← Previous Next →