Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwrap Result inside Optional [duplicate]

Tags:

rust

Is there a canonical way to convert Option<Result<T>> to Result<Option<T>>?

fn optres_to_resopt<T>(optres: Option<Result<T>>) -> Result<Option<T>> {
    if let Some(res) = optres {
        match res {
            Ok(v) => Ok(Some(v)),
            Err(e) => Err(e),
        }
    } else {
        Ok(None)
    }
}
like image 738
Mateen Ulhaq Avatar asked Jan 01 '23 08:01

Mateen Ulhaq


1 Answers

There is Option::transpose:

fn optres_to_resopt<T>(optres: Option<Result<T>>) -> Result<Option<T>> {
    optres.transpose()
}

And BTW, the implementation is basically your function:

pub fn transpose(self) -> Result<Option<T>, E> {
    match self {
        Some(Ok(x)) => Ok(Some(x)),
        Some(Err(e)) => Err(e),
        None => Ok(None),
    }
}
like image 138
edwardw Avatar answered Jan 02 '23 20:01

edwardw