rust - 为 Enum 实现 PartialEq,以便多个变体相等

标签 rust

我想定义一个枚举,其中两个不同的值相等,但是我想这样做而不必显式写出 Test::B == Test::B, Test::C = 的所有匹配情况= 测试::C.

pub enum Test {
    A,
    B,
    C,
    AlsoA,
}

也许是这样的,但不必写出注释标记部分

impl PartialEq for Test {
    fn eq(&self, other: &Test) -> bool {
        match (self, other) {
            (&Test::A, &Test::AlsoA) | (&Test::AlsoA, &Test::A) => true,

            // But without this part -------------------
            (&Test::A, &Test::A) => true,
            (&Test::B, &Test::B) => true,
            (&Test::C, &Test::C) => true,
            (&Test::AlsoA, &Test::AlsoA) => true,
            // -----------------------------------------

            _ => false,
        }
    }
}

最佳答案

可以在枚举中加入#[repr(T)](其中T是整数类型),然后比较它们的为T 值:

#[derive(Copy, Clone)]
#[repr(u8)]
pub enum Test {
    A,
    B,
    C,
    AlsoA,
}

impl PartialEq for Test {
    fn eq(&self, other: &Test) -> bool {
        match (self, other) {
            (&Test::A, &Test::AlsoA) |
            (&Test::AlsoA, &Test::A) => true,
            (x, y) => *x as u8 == *y as u8,
        }
    }
}

fn main() {
    use Test::*;
    assert!(A == A);
    assert!(B == B);
    assert!(C == C);
    assert!(AlsoA == AlsoA);
    assert!(A == AlsoA);
    assert!(AlsoA == A);
}

这也回答了你的第二个问题:只需添加一个 #[repr(T)] 然后使用 as T

关于rust - 为 Enum 实现 PartialEq,以便多个变体相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959528/

相关文章:

windows - cargo 登记更新总是失败

rust - 通用结构的过滤向量

rust - 设置 GTK 应用程序标题

rust - * mut(dyn std::ops::Fn()+ 'static)`无法使用serde::de::DeserializeOwned结构在线程之间安全共享

sqlite - 如何使用 Diesel 将 i64 与 Insertable 结合使用

json - 根据 JSON 中的字段有条件地解码 JSON

regex - 如何从传递给regex::Regex::replace的闭包中冒出一个错误?

rust - 引用和变异id_tree Rust的问题

rust - 如何阻止子进程的标准输入并忽略其标准输出?

arrays - 如何从 &str 转换为 [i8; 256]