得出特定变体的性状

时间:2019-03-05 20:45:11

标签: enums rust traits

假设我有以下枚举

enum MyEnum {
  VariantA,
  VariantB,
  VariantC,
}

这样做可以得出整个枚举的PartialEq特征

#[derive(PartialEq)]
enum MyEnum {
  VariantA,
  VariantB,
  VariantC,
}

我想做的是派生特征,但仅适用于特定的变体而不是整个枚举。那可能吗? (或者甚至有意义吗?)。

2 个答案:

答案 0 :(得分:2)

  

我想做的是派生特征,但仅适用于特定的变体而不是整个枚举。那可能吗? (或者甚至有意义吗?)。

这真的没有道理。

特征是针对类型实现的。枚举是一种类型,其变体是其值。您的问题等同于询问您是否可以对某些String实施特质,而对其他{}不实施。

如果不支持的变体始终返回false是可接受的,类似于f32的{​​{1}}实现在您比较PartialEq时返回false的方式值,那么您可以手动编写该impl:

NaN

请注意,您必须以这种方式实现impl PartialEq for MyEnum { fn eq(&self, other: &MyEnum) -> bool { use MyEnum::*; match (self, other) { // VariantA and VariantB are supported (VariantA(value), VariantA(other_value)) => value == other_value, (VariantB(value), VariantB(other_value)) => value == other_value, // Any other combinations of variants end up here _ => false, } } } ,因为Eq的实现可能被假定为 total ,但这不是。

答案 1 :(得分:2)

假设您的设置类似于:

#[derive(PartialEq)]
struct VarB{
    pub value: u32,
}

#[derive(PartialEq)]
enum MyEnum{
    VarA(VarA),
    VarB(VarB)
}

VarA来自不同的板条箱,由于它没有派生PartialEq(或任何其他外部特征),因此无法编译。

您可以使用newtype模式解决此问题(假设您有权访问relevent字段/访问器)

struct MyVarA(VarA);

impl PartialEq for MyVarA{
    fn eq(&self, other: &MyVarA) -> bool {
        self.0.value == other.0.value
    }

    fn ne(&self, other: &MyVarA) -> bool {
        self.0.value != other.0.value
    }
}

#[derive(PartialEq)]
struct VarB{
    value: u32,
}

#[derive(PartialEq)]
enum MyEnum{
    VarA(MyVarA),
    VarB(VarB)
}

更多信息: https://doc.rust-lang.org/rust-by-example/generics/new_types.html