Unzip Splits Pairs Into Two Collections
Split an iterator of pairs into two independent vectors with unzip, then recombine them with zip, whose result follows the shorter input side.
Code
fn main() {
// 一串 (城市, 人口) 记录
let records = vec![
("lisbon", 545_000u64),
("porto", 231_000),
("faro", 118_000),
];
// unzip:把成对序列一次性拆成两个独立集合
let (names, populations): (Vec<&str>, Vec<u64>) = records.into_iter().unzip();
println!("names: {names:?}");
println!("populations: {populations:?}");
// zip 是逆操作:把两条序列重新合成为对
let paired: Vec<(&str, u64)> = names
.iter()
.copied()
.zip(populations.iter().copied())
.collect();
println!("re-paired: {paired:?}");
// 长度不等时 zip 以短的一侧为准
let zipped: Vec<(u8, char)> = [1u8, 2, 3].iter().zip(['x', 'y']).copied().collect();
println!("zip stops at shorter side: {zipped:?}");
}What the code does
Count the function main as the entire surface area of Unzip Splits Pairs Into Two Collections.
Applying it
The run emits 4 labeled sections — names:, populations:, re-paired:, zip stops at shorter side: — one per step.
Statements that matter
let zipped: Vec<(u8, char)> = [1u8, 2, 3].iter().zip(['x', 'y']).copied().collect();
.zip(populations.iter().copied())
.collect();
Interactive Tools for This Topic
FAQ
- What does Unzip Splits Pairs Into Two Collections print when run?
- Execute the whole file; each printed line is prefixed with a label like `names:`, `populations:`, `re-paired:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.