英文:
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) -> 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<i64>,
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论