Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Any ways to run the Ok branch if the result gives Err when matching

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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`.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading