简体   繁体   English

如何实现枚举及其各自变体的特征?

[英]How do I implement a trait for an enum and its respective variants?

I'm trying to use enum variants to capture data which is heterogeneous in nature (has different collections of fields) but which is of the same "type" from a protocol perspective. 我试图使用枚举变量来捕获本质上是异构的(具有不同的字段集合)但从协议角度来看属于相同“类型”的数据。 However, I'm not sure how to implement subtype-specific methods and traits. 但是,我不确定如何实现特定于子类型的方法和特征。 Here is a minimal example of how I can create an enumeration of Data and I can use enum variant constructors to specify the types, but if I implement a trait on the variant, calling that function is not something I've figured out how to do. 这是一个最小的示例,说明如何创建数据枚举以及可以使用枚举变量构造函数来指定类型,但是如果我在变量上实现特征,则无法确定调用该函数的方法。

use std::fmt;

enum Data {
    N(NData),
    S(SData),
}

struct NData {
    numeric: u32,
}

impl fmt::Display for NData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.numeric)
    }
}

struct SData {
    stringy: Vec<String>,
}

fn main() {
    let d_n: Data = Data::N(NData { numeric: 0x0 });
    let n = NData { numeric: 0xff };

    // Fails, fmt::Display not implemented for Data
    println!("{}", d_n);

    // Just fine!
    println!("{}", n);
}

One possible solution could be to implement your trait for the variants as well as for the enum , which as you can see here only calls the specific implementations of the variants: 一种可能的解决方案是为变体以及enum实现特征,正如您在此处看到的那样,它仅调用变体的特定实现:

use std::fmt;

struct NData {
    numeric: u32,
}

impl fmt::Display for NData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.numeric)
    }
}

struct SData {
    strings: Vec<String>,
}

impl fmt::Display for SData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self.strings)
    }
}

enum Data {
    N(NData),
    S(SData),
}

impl fmt::Display for Data {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Data::N(n_data) => n_data.fmt(f),
            Data::S(s_data) => s_data.fmt(f),
        }
    }
}

fn main() {
    let n = NData { numeric: 0xff };
    let s = SData { strings: vec!["hello".to_string(), "world".to_string()] };

    println!("{}", n);
    println!("{}", s);

    let d_n = Data::N(n);
    let d_s = Data::S(s);

    println!("{}", d_n);
    println!("{}", d_s);
}

Which will produce the following output: 这将产生以下输出:

255
["hello", "world"]
255
["hello", "world"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将所有变体实现相同特征的枚举转换为Rust中的框? - Converting an enum where all variants implement the same trait to a box in Rust? 如何在特征中使用枚举并在枚举中的结构上实现特征? Rust - How can I use enum in a trait and implement trait on structs that are in the enum? Rust 如何为可迭代变体的枚举实现 IntoIterator? - How to implement IntoIterator for an enum of iterable variants? 如何仅匹配枚举的一些变体,而不是所有变体? - How do I match only some, not all variants of an enum? 如何为实现该特征的现有类型的枚举实现范围内的特征? - How can I implement a trait in scope for an enum of existing types for which the trait is implemented? 在宏中匹配类似元组的枚举变体,其中枚举类型和变体是元变量:如何编写匹配模式? - Matching tuple-like enum variants in a macro, where enum type and variants are metavariables: how do I write the matching pattern? 不同的枚举变体如何在TypeScript中工作? - How do the different enum variants work in TypeScript? 如何在不知道其结构的情况下创建匹配枚举变体的宏? - How to create a macro that matches enum variants without knowing its structure? 如何在枚举单例中实现日志记录? - How do I implement logging in an enum singleton? 如何实现此公共可访问枚举 - How do I implement this public accesible enum
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM