Assert to confirm a single rust variant

I have a function that takes an enum parameter and I wish to use an assert macro that panics for all but one of the enum variants. What is the best way to do this?

To illustrate--- In the following code example, I'm looking for a way to write an assert macro I can place at the top of the "want_a_bar" function, that avoids the need for the noisier match statement. My attempts at this all seem to run into various problems and I'm hoping there is an obvious solution I am missing.

#[allow(dead_code)]
enum Foo {
      Bar(u16),
      FooBar
}

fn want_a_bar(foo: Foo) {
    match foo {
        Foo::Bar(_) => println!("All good here!"),
        _ => panic!("Expected a Bar got something else.")
    }
}

fn main() {
    let foo = Foo::Bar(8);
    want_a_bar(foo);
}

How about assert!(matches!(foo, Foo::Bar(_)))?

2 Likes

Thank you. That does it!

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.