Partition Results Into Ok And Err
Split parsed rows once with Iterator partition, then unwrap the valid half and unwrap_err the invalid half to keep values and reasons separate.
Code
fn main() {
// 混合成功与失败的解析结果
let rows = ["12", "x7", "300", "oops", "44"];
let results: Vec<Result<u32, String>> = rows
.iter()
.map(|row| row.parse::<u32>().map_err(|_| format!("{row} not numeric")))
.collect();
// partition 按谓词拆成两个集合:合法与非法一次分离
let (valid, invalid): (Vec<_>, Vec<_>) = results.into_iter().partition(|r| r.is_ok());
let numbers: Vec<u32> = valid.into_iter().map(|r| r.unwrap()).collect();
let reasons: Vec<String> = invalid.into_iter().map(|r| r.unwrap_err()).collect();
println!("valid: {numbers:?}");
println!("invalid: {reasons:?}");
}What the code does
Partition Results Into Ok And Err keeps everything in the function main.
Fallible operations return Result, forcing the caller to handle both arms explicitly.
What to watch for
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Applying it
The demo output is labeled (valid:, invalid:); each label names the call that printed it.
Statements that matter
let reasons: Vec<String> = invalid.into_iter().map(|r| r.unwrap_err()).collect();
let numbers: Vec<u32> = valid.into_iter().map(|r| r.unwrap()).collect();
let (valid, invalid): (Vec<_>, Vec<_>) = results.into_iter().partition(|r| r.is_ok());
Interactive Tools for This Topic
FAQ
- Is there exception handling?
- As `Result` values — each fallible call returns one, and the caller matches or propagates it.
- What does Partition Results Into Ok And Err print when run?
- Run it as a complete program — the output lines carry labels such as `valid:`, `invalid:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.