Take action when enum is not a particular value

Is there a more concise way to express this match?

fn main() {
    let s = Stuff::Foo(1);
    match s {
        Stuff::Foo(_) => (),
        _ => println!("Doing stuff")
    }
}

enum Stuff{
    Foo(u8),
    Bar(u16),
    Baz,
    Etc,
}

My actual enum has more discriminants so combining them with | in an if let binding is not really better.

How about this?

fn main() {
    let s = Stuff::Foo(1);
    if !s.is_foo() {
        println!("Doing stuff");
    }
}

enum Stuff{
    Foo(u8),
    Bar(u16),
    Baz,
    Etc,
}

impl Stuff {
    fn is_foo(&self) -> bool {
        match self {
            Stuff::Foo(_) => true,
            _ => false,
        }
    }
}
if !matches!(s, Stuff::Foo(_)) {
    println!("Doing stuff")
}

using the new matches! macro, stable since 1.42.0

3 Likes

If you can't tolerate !double! !exclamation! !marks!, here's an alternative:

use std::ops::Not;

if matches!(s, Stuff::Foo(_)).not() {
    println!("Doing stuff");
}

(for fun)

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.