Map While Collects The Valid Prefix
map_while fuses mapping and truncation: iteration stops at the first item whose parse fails, so only the valid prefix of the feed is ever touched.
Code
fn parse_prefix(items: &[&str]) -> Vec<u32> {
// map_while:映射直到首个 None 就停,前缀之外的数据完全不碰
items.iter().map_while(|item| item.parse::<u32>().ok()).collect()
}
fn main() {
let feed = ["12", "34", "56", "bad", "78"];
println!("valid prefix: {:?}", parse_prefix(&feed));
// 全部合法时取完整序列
let clean = ["1", "2", "3"];
println!("clean: {:?}", parse_prefix(&clean));
// 首个就失败:得到空 Vec 而不是报错
let broken = ["x", "2"];
println!("broken: {:?}", parse_prefix(&broken));
}How the snippet works
Map While Collects The Valid Prefix is built around the functions parse_prefix and main.
Applying it
The primary signature is fn parse_prefix(items: &[&str]) -> Vec<u32>
Running the file prints labeled results such as valid prefix:, clean:, broken: — each operation’s effect is visible in the output.
Execute the file and main walks through parse_prefix, in that order.
Statements that matter
items.iter().map_while(|item| item.parse::<u32>().ok()).collect()
}
Interactive Tools for This Topic
FAQ
- What does Map While Collects The Valid Prefix print when run?
- The script runs standalone; its 3 labeled outputs include `valid prefix:`, `clean:`, `broken:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.