My first thought is to map
the Option
, but I can't use try!
from inside of the closure. The match
statement looks unnecessary, but I can't figure out how to simplify it.
fn example<T, E>(val: Option<Result<T, E>>) -> Result<Option<T>, E> {
Ok(match val {
Some(v) => Some(v?),
None => None
})
}
Result<T, E> is the type used for returning and propagating errors. It is an enum with the variants, Ok(T) , representing success and containing a value, and Err(E) , representing error and containing an error value.
Type Option represents an optional value: every Option is either Some and contains a value, or None , and does not. Option types are very common in Rust code, as they have a number of uses: Initial values. Return values for functions that are not defined over their entire input range (partial functions)
In Rust 1.33, transpose()
is stable, so you can just call it:
fn main() {
let x: Result<Option<i32>, ()> = Ok(Some(5));
let y: Option<Result<i32, ()>> = Some(Ok(5));
assert_eq!(x, y.transpose());
}
You can use Option::map_or()
:
val.map_or(Ok(None), |v| v.map(Some))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With