Iterator Collect Into Result Short Circuits
Collect a mapped iterator into Result so the first parse failure short-circuits the whole batch, and switch to filter_map for partial data.
Code
fn main() {
let rows = ["120", "34", "7", "256"];
// collect 到 Result<Vec<_>, _>:全部成功才得到 Ok
let parsed: Result<Vec<i32>, _> = rows.iter().map(|r| r.parse::<i32>()).collect();
match parsed {
Ok(values) => println!("all parsed: {:?}", values),
Err(e) => println!("first failure: {}", e),
}
// 含非法项:首个错误短路(short-circuit)整批,已成功的项被丢弃
let mixed = ["120", "oops", "7"];
let attempt: Result<Vec<i32>, _> = mixed.iter().map(|r| r.parse::<i32>()).collect();
match attempt {
Ok(values) => println!("all parsed: {:?}", values),
Err(e) => println!("first failure: {}", e),
}
// 允许部分数据:filter_map 丢弃解析失败的项
let partial: Vec<i32> = mixed.iter().filter_map(|r| r.parse::<i32>().ok()).collect();
println!("partial: {:?}", partial);
}What the code does
Count the function main as the entire surface area of Iterator Collect Into Result Short Circuits.
The function returns Result, so handling the error arm is not optional. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.
Points of care
- The
?operators are load-bearing: delete one and the error handling becomes your job.
Applying it
The demo output is labeled (all parsed:, first failure:, partial:), so every printed line maps back to its originating operation.
Statements that matter
let attempt: Result<Vec<i32>, _> = mixed.iter().map(|r| r.parse::<i32>()).collect();
let parsed: Result<Vec<i32>, _> = rows.iter().map(|r| r.parse::<i32>()).collect();
let partial: Vec<i32> = mixed.iter().filter_map(|r| r.parse::<i32>().ok()).collect();
Interactive Tools for This Topic
FAQ
- What happens when a call fails?
- Through `Result` values. Nothing panics inside the snippet; the caller decides how to handle each failure.
- What does Iterator Collect Into Result Short Circuits print when run?
- No setup needed: run the file and look for labeled lines like `all parsed:`, `first failure:`, `partial:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.