I would definitely use transpose
(from the approved answer) but as an exercise here is a different version of implementation:
fn optres_to_resopt<T, E>(optres: Option<Result<T, E>>) -> Result<Option<T>, E> {
optres.map_or(Ok(None), |x| Ok(Some(x?)))
}
Playground
Since Result
also has a transpose
method too, it is easy to revert it back. As an alternative we can apply the same approach in this problem too:
fn resopt_optres<T, E>(resopt: Result<Option<T>, E>) -> Option<Result<T, E>> {
resopt
.map(|x| Some(Ok(x?)))
.unwrap_or_else(|x| Some(Err(x)))
}
Playground
Note : The idea in here is map_or
(or unwap_or_else
) has ability to change the enclosing type with a generic type.