raindust
raindust

Reputation: 45

How to deal with errors gracefully in map method of Option?

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);

Upvotes: 1

Views: 1297

Answers (1)

kmdreko
kmdreko

Reputation: 60112

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);

Upvotes: 3

Related Questions