Quick check on a Result<Enum, ...>?

Is it possible to do a "one liner" quick if on a Result<Enum, Err> where Enum has multiple values but you only want to check one real quick?

Basically something like if !result.has_ok_value(Enum::SpecificCase) { ... }

I'm finding these cases quite cumbersome usually taking 4+ lines of code for no good reason and mostly I'm having trouble avoiding a "duplicate else".

E.g. I can do:

        if let Some(enum) = &result.ok() {
            if *enum != Enum::SomeValue {
                do_the_stuff();
            }
        } else {
            do_the_stuff();
        }

Same with using match where I need to double-match and use do_the_stuff multiple times too.

Maybe:

enum E {
    Value1,
    Value2,
}

fn main() {
    let rs: Result<E, ()> = Ok(E::Value1);
    if let Ok(E::Value1) = rs {
        //...
    }else{
        //...
    }
}
1 Like

Or you can match like:

match result {
    Ok(Enum::SomeValue) => {}
    _ => {}
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.