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
zipstops when the shorter side runs out.unzipneeds the target types annotated.partitionsplits on a predicate into two collections.
Keywords and builtins used here
Vecfni32letmainstr
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.
Step 5 of 5 in Adapters, step 5 of 14 in Iterators & closures.