Pad Uneven Sides Before Zip
Plain zip silently drops the longer side tail, so pad the short side with repeat and chain to equal length before pairing records.
Code
use std::iter;
fn main() {
let names = ["ada", "bob"];
let scores = [91, 84, 77, 63];
// 直接 zip:以短侧为准,长侧尾部被静默丢弃
let zipped: Vec<(&str, i32)> = names.iter().zip(scores.iter().copied()).collect();
println!("plain zip: {zipped:?}");
// pad the short side to equal length before zipping:
// chain 接上 repeat 占位值,把名字侧补到与成绩等长
let padded: Vec<(String, i32)> = names
.iter()
.map(|n| n.to_string())
.chain(iter::repeat("n/a".to_string()).take(scores.len() - names.len()))
.zip(scores.iter().copied())
.collect();
println!("padded: {padded:?}");
}Reading the snippet
The active pieces are the function main.
What to watch for
- Everything it calls is documented as part of the language core.
Using it
Entry signature: fn main()
The file tags its output — plain zip:, padded: — when the file runs.
Key statements
let zipped: Vec<(&str, i32)> = names.iter().zip(scores.iter().copied()).collect();
.zip(scores.iter().copied())
.collect();
Interactive Tools for This Topic
FAQ
- What does Pad Uneven Sides Before Zip print when run?
- Execute the whole file; each printed line is prefixed with a label like `plain zip:`, `padded:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.