Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extracting varying, parameterized 'new' methods to trait

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading