typestar

zip, unzip and partition in Rust

Pairing two streams, tearing pairs apart, splitting one stream in two.

fn main() {
    let names = ["ada", "grace", "alan"];
    let stars = [3, 2, 1];

    let paired: Vec<(&&str, &i32)> = names.iter().zip(stars.iter()).collect();
    println!("{:?}", paired);

    let (who, score): (Vec<&str>, Vec<i32>) =
        names.iter().copied().zip(stars.iter().copied()).unzip();
    println!("{:?} {:?}", who, score);

    let (pass, fail): (Vec<i32>, Vec<i32>) =
        (1..=10).partition(|n| n % 3 == 0);
    println!("{:?} {:?}", pass, fail);
}

How it works

  1. zip stops when the shorter side runs out.
  2. unzip needs the target types annotated.
  3. partition splits on a predicate into two collections.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
425
Tokens
184
Three-star pace
95 tpm

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

Type this snippet

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

← Previous Next →