Derive a Trait for particular variants

前端 未结 2 1562

Let\'s say I have the following Enum

enum MyEnum {
  VariantA,
  VariantB,
  VariantC,
}

I can derive the PartialEq trait for the whole enum by

2条回答
  •  梦毁少年i
    2021-01-22 16:07

    Assuming you have a setup like:

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

    VarA comes from a different crate and you can't compile due to it not having derived PartialEq (or any other external trait).

    You can solve that with the newtype pattern (assuming you have access to the relevent fields / accessors)

    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)
    }
    

    further informations: https://doc.rust-lang.org/rust-by-example/generics/new_types.html

提交回复
热议问题