Pongsaphol Pongsawakul
Pongsaphol Pongsawakul

Reputation: 193

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?

Upvotes: 2

Views: 1614

Answers (2)

jthulhu
jthulhu

Reputation: 8688

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>.

Upvotes: 3

Netwave
Netwave

Reputation: 42786

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.

Upvotes: 9

Related Questions