为Enum设置PartialEq以使多个变量相等

时间:2016-06-22 05:48:42

标签: 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,
        }
    }
}

1 个答案:

答案 0 :(得分:5)

您可以将#[repr(T)]添加到枚举(其中T是整数类型),然后比较它们的as 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