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

Ignore the result type in case of success while bubbling up errors from another function?

In one of my functions (my_fun()), depending on the value of a boolean, I want to call different functions from an external crate. Those two functions have a different return type. For example, return_u64() returns a Result<u64, Error> while return_nothing() returns Result<(), Error>.

In my_fun(), I don’t really care about the return type when it is a success, but I want to be able to bubble up the errors from return_u64() and return_nothing() if one of them fails.

To sum up, this is what I have now:

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

use std::fmt::Error;

// Those functions come from an external crate -----------------------------
fn return_u64() -> Result<u64, Error> {
    Ok(0 as u64)
}
fn return_nothing() -> Result<(), Error> {
    Ok(())
}
// -------------------------------------------------------------------------

fn my_fun(foo: bool) -> Result<(), Error> {
    if foo {
        let out = return_u64()?;
        return Ok(out);
    } else {
        let out = return_nothing()?;
        return Ok(out);
    }
}

fn main() {}

But of course this won’t compile since the first block returns a u64 while the function expects ().

I don’t really care whether this function returns () or u64. Is there a way to "harmonize" the return type in case of success while returning the original error message from return_u64() or return_nothing() if one of them fails?

>Solution :

You can just map whatever actual type to () and return it

fn my_fun(foo: bool) -> Result<(), Error> {
    if foo {
        let out = return_u64().map(|_| ())?;
        return Ok(out);
    } else {
        let out = return_nothing()?;
        return Ok(out);
    }
}

Or similarly map the () to some stub u64 value

fn my_fun(foo: bool) -> Result<u64, Error> {
    if foo {
        let out = return_u64()?;
        return Ok(out);
    } else {
        let out = return_nothing().map(|_| 0)?;
        return Ok(out);
    }
}
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