RRust By Example
intermediateIterators

Iterator Zip

Combine two iterators with zip.

Iterator Zip

Combine two iterators with zip.

Difficulty

Intermediate

Code

rust
fn main() {
    let names = vec!["Alice", "Bob", "Charlie"];
    let scores = vec![95, 87, 92];

    let pairs: Vec<_> = names.iter().zip(scores.iter()).collect();
    println!("pairs: {:?}", pairs);

    for (name, score) in names.iter().zip(scores.iter()) {
        println!("{}: {}", name, score);
    }

    // zip with index-like iterator
    let items = vec!["a", "b", "c", "d"];
    let numbered: Vec<_> = (1..).zip(items).collect();
    println!("numbered: {:?}", numbered);
}

Explanation

zip pairs elements from two iterators.

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