From 2be9574ce8a6cdce85deb56223d967f4f95b097a Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Fri, 25 Feb 2022 10:24:33 -0800 Subject: [PATCH] Add an example of collecting errors while iterating successes Inspired by the comments from people looking for something like this in . --- src/error/iter_result.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/error/iter_result.md b/src/error/iter_result.md index 3b03090d5d..e77e21ff6f 100644 --- a/src/error/iter_result.md +++ b/src/error/iter_result.md @@ -30,6 +30,25 @@ fn main() { } ``` +## Collect the failed items with `map_err()` and `filter_map()` + +`map_err` calls a function with the error, so by adding that to the previous +`filter_map` solution we can save them off to the side while iterating. + +```rust,editable +fn main() { + let strings = vec!["42", "tofu", "93", "999", "18"]; + let mut errors = vec![]; + let numbers: Vec<_> = strings + .into_iter() + .map(|s| s.parse::()) + .filter_map(|r| r.map_err(|e| errors.push(e)).ok()) + .collect(); + println!("Numbers: {:?}", numbers); + println!("Errors: {:?}", errors); +} +``` + ## Fail the entire operation with `collect()` `Result` implements `FromIter` so that a vector of results (`Vec>`)