如何在没有模式匹配的情况下比较枚举 [英] How to compare enum without pattern matching

查看:59
本文介绍了如何在没有模式匹配的情况下比较枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在迭代器上应用 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 ,但仍在讨论中。

这篇关于如何在没有模式匹配的情况下比较枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆