'Convert Option<Result<T, E>> to Option<T>

Is there a simple way to convert an Option<Result<T, E>> to an Option<T>, returning Err in case of error?



Solution 1:[1]

You can use transpose, which does exactly that.

fn main() -> Result<(), String> {
    let _foo: Option<usize> = Some(Err("Foo".to_string())).transpose()?;
    Ok(())
}

Playground

Notice that it transformst the Option<Result<T, E>> to Result<Option<T>, E>. You would just need to use the ? or unrwrap/except methods to take the Option<T> if is not an E.

Solution 2:[2]

Assuming your function does return something like Return<_> (so that you can actually return an Err), an easy way would be: let b = a.transpose()?; where a: Option<Result<T, E>> and b: Option<T>.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Netwave
Solution 2