How to stop iteration and return an error when Iterator::map returns Result::Err?
Hello, experienced Rustaceans! I'm new to Rust and have been struggling with a problem for several hours. I have a vector of strings that I want to convert to numbers using `Iterator::map` and `str::parse::()`. The problem is that `parse` returns a `Result`, and if any string is not a number, I want to immediately stop the entire iteration and return an error to the calling code.
Here's my code:
```rust
fn parse_numbers(input: Vec<&str>) -> Vec {
input.iter().map(|s| s.parse::().unwrap()).collect()
}
```
`unwrap()` panics, but I need an elegant solution without panicking. I tried using `filter_map`, but it just ignores errors, and I need to propagate them. I also tried wrapping everything in `Result`:
```rust
fn parse_numbers(input: Vec<&str>) -> Result, ParseIntEr
No answers yet.
Log in to leave an answer
Blogs