我想定义一个枚举,其中两个不同的值相等,但是我想这样做而不必显式写出 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/