Iterator Zip Pairs Two Sequences

Zip two iterators into lazy pairs that stop at the shorter side, combining enumerate or ranges for indexed and numbered pairing.

RustData Integrity

Code

rustsnippet
25 lines
fn main() {
    let names = ["orders", "billing", "auth"];
    let replicas = [3, 1, 9];

    // zip 惰性配对成元组,任一侧耗尽即停止
    let deployed: Vec<String> = names
        .iter()
        .zip(replicas.iter())
        .map(|(name, count)| format!("{name}x{count}"))
        .collect();
    println!("deployed: {deployed:?}");

    // 与无限 range 组合得到带编号的配对
    let ranked: Vec<(i32, &str)> = names
        .iter()
        .zip(1..)
        .map(|(name, rank)| (rank, *name))
        .collect();
    println!("ranked: {ranked:?}");

    // 长度不等时以较短一侧为准:4 个元素只产出 3 对
    let extra = [1, 2, 3, 4];
    let zipped: Vec<(i32, &str)> = extra.iter().copied().zip(names.iter()).collect();
    println!("zipped: {zipped:?}");
}

What the code does

Iterator Zip Pairs Two Sequences reduces to the function main.

Applying it

Running the file prints labeled results such as deployed:, ranked:, zipped: — each operation’s effect is visible in the output.

Statements that matter

let zipped: Vec<(i32, &str)> = extra.iter().copied().zip(names.iter()).collect();
.zip(replicas.iter())
.map(|(name, count)| format!("{name}x{count}"))
.collect();
.map(|(name, rank)| (rank, *name))
.collect();

Interactive Tools for This Topic

FAQ

What does Iterator Zip Pairs Two Sequences print when run?
No setup needed: run the file and look for labeled lines like `deployed:`, `ranked:`, `zipped:` in the output.