Reputation: 193
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
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
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(())
}
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