Attribute Macro impl_tools::impl_default

source ·
#[impl_default]
Expand description

Impl Default with given field or type initializers

This macro may be used in one of two ways.

Type-level initializer

/// A simple enum; default value is Blue
#[impl_default(Colour::Blue)]
enum Colour {
    Red,
    Green,
    Blue,
}

fn main() {
    assert!(matches!(Colour::default(), Colour::Blue));
}

A where clause is optional: #[impl_default(EXPR where BOUNDS)].

Field-level initializer

This variant only supports structs. Fields specified as name: type = expr will be initialized with expr, while other fields will be initialized with Default::default().

impl_scope! {
    #[impl_default]
    struct Person {
        name: String = "Jane Doe".to_string(),
        age: u32 = 72,
        occupation: String,
    }
}

fn main() {
    let person = Person::default();
    assert_eq!(person.name, "Jane Doe");
    assert_eq!(person.age, 72);
    assert_eq!(person.occupation, "");
}

A where clause is optional: #[impl_default(where BOUNDS)].