rust

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:

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);
        }
    }