Skip to main content

Constructor

Derive Macro Constructor 

Source
#[derive(Constructor)]
{
    // Attributes available to this derive:
    #[new]
}
Expand description

Adds a new() constructor that accepts each field as a parameter. The method is private by default. Use #[new("pub")] or #[new("pub(crate)")] to set a custom visibility.

ยงExample

#[derive(Constructor)]
struct MyStruct {
    name: String,
    count: i32,
}

adds

impl MyStruct {
    fn new(name: String, count: i32) -> Self {
        Self { name, count }
    }
}

With a visibility attribute:

#[derive(Constructor)]
#[new(pub(crate))]
struct MyStruct(usize);

adds

impl MyStruct {
    pub(crate) fn new(_0: usize) -> Self {
        Self(_0)
    }
}