snippetrustCritical
How to compare enum without pattern matching
Viewed 0 times
enumhowmatchingwithoutpatterncompare
Problem
I want to apply
I would rather write something like this:
This gives me a compile error
Is there an alternative to the verbose pattern matching? I looked for a macro but couldn't find a suitable one.
filter on an iterator and I came up with this one and it works, but it's super verbose:.filter(|ref my_struct| match my_struct.my_enum { Unknown => false, _ => true })I would rather write something like this:
.filter(|ref my_struct| my_struct.my_enum != Unknown)This gives me a compile error
binary operation != cannot be applied to type MyEnum
Is there an alternative to the verbose pattern matching? I looked for a macro but couldn't find a suitable one.
Solution
Use
Alternatively, you can use
Then your "ideal" variant will work as is. However, this requires that
matches!, e.g.:matches!(my_struct.my_enum, Unknown)Alternatively, you can use
PartialEq trait, for example, by #[derive]:#[derive(PartialEq)]
enum MyEnum { ... }Then your "ideal" variant will work as is. However, this requires that
MyEnum's contents also implement PartialEq, which is not always possible/wanted.Code Snippets
matches!(my_struct.my_enum, Unknown)#[derive(PartialEq)]
enum MyEnum { ... }Context
Stack Overflow Q#25576748, score: 184
Revisions (0)
No revisions yet.