Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to convert Option<Result<T, E>> to a Result<Option<T>, E> without using match?

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
    })
}
like image 333
GregoryComer Avatar asked Apr 02 '17 08:04

GregoryComer


People also ask

What does result () mean Rust?

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.

What is option in Rust?

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)


2 Answers

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());
}
like image 191
Stargateur Avatar answered Sep 30 '22 14:09

Stargateur


You can use Option::map_or():

val.map_or(Ok(None), |v| v.map(Some))
like image 41
Ry- Avatar answered Sep 29 '22 14:09

Ry-