Problem while comparing enum values in matches!() macro

even though b & a are not matching, I'm able to execute things which are inside if statement. why is it so?

enum Myenum {
    Foo,
    Bar,
}

fn main() {
    let a = Myenum::Foo;
    let b = Myenum::Bar;

    if matches!(b, a) {
        println!("matching");
    }
}

o/p:
matching

The left hand side of matches!() is a pattern, so b will be interpreted as value binding, which always succeeds. matches!(b, a) expands to matches a { b => true, _ => false }.

1 Like

How should i resolve this?

Derive PartialEq and Eq and use ==.

1 Like

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.