Can Result contain both Element T and Error?

From Rust doc:

Result<T, E> could have one of two outcomes:

So I am assuming it cannot have both? I am trying to do something in a function that may potentially result in a recoverable error. I want to both do recovery and return the error if possible. However, not sure what is the idiomatic way to do that in Rust, or can/should it be done at all.

For reference, I have the following code:

extern crate anyhow;
fn divide(a:f64, b:f64) ->  Result<f64, anyhow::Error>{
    if b==0.0 {
        return Err(anyhow::anyhow!("Divide by zero"));
    }
    Ok(a/b)

}


fn main() {
    let r=divide(3.0,0.0);
    match r {
        Ok(d) => {
            println!("Result: {}",d);
        }
        Err(e) => {
            println!("Error: {}",e);
        }
    }
}

Can I get a default result of 1.0 even if the Divide by zero occur?
Thank you.

It is defined as

pub enum Result<T, E> {
    Ok(T),
    Err(E),
}

so no, it cannot contain both, only either Ok(T) or Err(E).

1 Like

It's guaranteed that it's only one of these. Also match guarantees that only one arm will be executed.

3 Likes

If it's about storing data in both result cases to optionally recover, you can simply have T and E be the same type or use a type for E, that makes it possible to obtain a T from it. An example for the latter is LockResult from the standard library.

2 Likes

I've been using Result<WithWarnings<T, W>, E> to represent a fallible return value with non-fatal errors (warnings) of type W and fatal errors of type E, where

pub struct WithWarnings<T, W> {
    value: T,
    warnings: W,
}

(Note in general W will represent a combination of warnings, not just one as with typical error enums.) It seems to work pretty well but of course every use-case is different.

2 Likes