How to compare enum without pattern matching

Christoph picture Christoph · Aug 29, 2014 · Viewed 28.6k times · Source

I want to apply 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.

Answer

Vladimir Matveev picture Vladimir Matveev · Aug 30, 2014

First, 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.

Second, you can implement a macro yourself, something like this (though this macro does not support all kinds of patterns, for example, alternatives):

macro_rules! matches(
    ($e:expr, $p:pat) => (
        match $e {
            $p => true,
            _ => false
        }
    )
)

Then you would use it like this:

.filter(|ref my_struct| !matches!(my_struct.my_enum, Unknown))

There is an RFC to add such a macro into the standard library, but it is still under discussion.