提取可变的、参数化的“新”方法到特征

huangapple go评论73阅读模式
英文:

Extracting varying, parameterized 'new' methods to trait

问题

我对Rust还很陌生,刚刚遇到了这个问题。

我有许多不同的结构体,它们都实现了自己的new方法,具有不同数量和类型的输入参数。每个new方法都做类似于这样的事情:

impl MyStruct {
    pub fn new(param1: String, param2: u32, param3: char) -> Self {
        MyStruct {
            id: None,
            param1,
            param2,
            param3,
        }
    }
}

实现这个new方法的每个结构体都具有相同的一般结构,但字段的类型和数量不同:

pub struct MyStruct {
    pub id: Option<i64>,
    pub param1: String,
    pub param2: u32,
    pub param3: char,
    // 更多参数
}

手动在每个结构体上实现new方法似乎存在大量的代码重复。是否有一种方法可以将此功能提取到一个trait中?

最初我考虑使用枚举或泛型作为trait中的new方法的参数,但无法想出一个具体的解决方案。

英文:

I'm new to Rust and just bumped into this issue.

I have many different structs, that all implement their own new methods, with a varying number of input parameters and types. Every new method does something like this:

impl MyStruct {
    pub fn new(param1: String, param2: u32, param3: char) -&gt; Self {
        MyStruct {
            id: None,
            param1,
            param2,
            param3,
        }
    }
}

Every struct that implements this new method has the same general structure, with varying types and amounts of fields:

pub struct MyStruct {
    pub id: Option&lt;i64&gt;,
    pub param1: String,
    pub param2: u32,
    pub param3: char,
    // more params
}

Manually implementing the new method on every struct seems like a lot of code repetition. Is there some way to extract this functionality into a trait?

I initially thought of using enums or generics as the parameters of the new method in the trait, but couldn't come up with a concrete solution.

答案1

得分: 0

由于不同的签名,您将无法对此使用特性。枚举和泛型也是如此。如果您的new关联函数很简单且不需要进行任何计算,可以使用derive-new crate。

英文:

Due to the different signatures, you won't be able to use a trait for this. Same with enums and generics. There is the derive-new crate you could use if your new associated functions are simple and don't require any computation done in them.

huangapple
  • 本文由 发表于 2023年3月7日 23:33:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75664016.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定