Skip to main content

auto_default

Attribute Macro auto_default 

Source
#[auto_default]
Expand description

Adds a default field value of Default::default() to fields that don’t have one

§Example

Turns this:

#[auto_default]
struct User {
    age: u8,
    is_admin: bool = false
}

Into this:

struct User {
    age: u8 = Default::default(),
    is_admin: bool = false
}

This macro applies to structs with named fields, and enums.

§Do not add = Default::default() field value to select fields

If you do not want a specific field to have a default, you can opt-out with #[auto_default(skip)]:

#[auto_default]
struct User {
    #[auto_default(skip)]
    age: u8,
    is_admin: bool
}

The above is transformed into this:

struct User {
    age: u8,
    is_admin: bool = Default::default()
}