I have a match branch that theoretically resolves the Error (if I do have one) condition, which then I would want to execute whatever code I’ve written in the Ok() branch above.
Is it possible to do that in Rust?
Example:
let foo: Result<Bar, Error> = some_func();
match foo {
Ok(bar) => { Something happens here }
Err(e) => { Resolves error, and execute the Ok() case above }
}
>Solution :
You can use unwrap_or_else to handle errors and replace them with a new bar. Then put the Ok code below it where you’re guaranteed to have a bar.
let foo: Result<Bar, Error> = some_func();
let bar = foo.unwrap_or_else(|e| {
// Resolve the error and return a replacement `bar`.
new_bar
});
// Proceed with `bar`.