1

In the Rust By Example book show us a way to handle errors in the map method of Iterator:

 let strings = vec!["93", "tofu", "18"]; let numbers: Result<Vec<_>, _> = strings.into_iter().map(|s| s.parse::<i32>()).collect(); println!("Results: {:?}", numbers); 

Is it a similar way to deal with errors in Option like the following?

 let a: Option<&str> = Some("tofu"); let b: Result<Option<i32>, _> = a.map(|a| a.parse::<i32>()); println!("Results: {:?}", b); 

1 Answer 1

3

There is a handy method called .transpose() that can convert an Option<Result<T, E>> into a Result<Option<T>, E> (or the reverse):

let a: Option<&str> = Some("tofu"); let b: Result<Option<i32>, _> = a.map(|a| a.parse::<i32>()).transpose(); println!("Results: {:?}", b); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.