得出特定变体的性状 [英] Derive a Trait for particular variants

查看:70
本文介绍了得出特定变体的性状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下枚举

enum MyEnum {
  VariantA,
  VariantB,
  VariantC,
}

我可以通过以下方式得出整个枚举的PartialEq特征

I can derive the PartialEq trait for the whole enum by doing so

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

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

What I want to do, is derive the trait but only to particular variants and not the whole enum. Is that possible? (or does it even make sense?).

推荐答案

假设您有这样的设置:

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

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

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

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

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

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

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

这篇关于得出特定变体的性状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆