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.
>Solution :
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.