如何在没有模式匹配的情况下比较枚举

问题描述:

我想在迭代器上应用 filter ,我想到了这一点,它可以工作,但是它太冗长了:

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 })

我宁愿这样写:

.filter(|ref my_struct| my_struct.my_enum != Unknown)

这给了我一个编译错误

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.

首先,可以使用 PartialEq 特性,例如,通过#[derive]

First, you can use PartialEq trait, for example, by #[derive]:

#[derive(PartialEq)]
enum MyEnum { ... }

然后,您的理想变体将按原样工作。但是,这要求 MyEnum 的内容还必须实现 PartialEq ,但这并不总是可能/不需要的。

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))

将这种宏添加到标准库中的RFC ,但仍在讨论中。