Skip to content

Commit 5ad4f97

Browse files
authored
Merge pull request #1509 from scottmcm/map-err-ok
Add an example of collecting errors while iterating successes
2 parents 21807dc + 2be9574 commit 5ad4f97

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/error/iter_result.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,25 @@ fn main() {
3030
}
3131
```
3232

33+
## Collect the failed items with `map_err()` and `filter_map()`
34+
35+
`map_err` calls a function with the error, so by adding that to the previous
36+
`filter_map` solution we can save them off to the side while iterating.
37+
38+
```rust,editable
39+
fn main() {
40+
let strings = vec!["42", "tofu", "93", "999", "18"];
41+
let mut errors = vec![];
42+
let numbers: Vec<_> = strings
43+
.into_iter()
44+
.map(|s| s.parse::<u8>())
45+
.filter_map(|r| r.map_err(|e| errors.push(e)).ok())
46+
.collect();
47+
println!("Numbers: {:?}", numbers);
48+
println!("Errors: {:?}", errors);
49+
}
50+
```
51+
3352
## Fail the entire operation with `collect()`
3453

3554
`Result` implements `FromIter` so that a vector of results (`Vec<Result<T, E>>`)

0 commit comments

Comments
 (0)