#default #field #struct #struct-fields #macro #getter

macro default_fields

A simple derive macro that adds a default getter function for each struct field

1 unstable release

0.1.0 Oct 8, 2024

#1013 in Procedural macros

MIT license

4KB

DefaultFields

Simple Rust derive macro that, for each field in the struct, creates a function that returns its default value (requires the struct to extend Default trait). This is useful if you want to parse struct from JSON and fill in the missing elements with defaults. For example, the following code:

#[derive(Deserialize)]
struct TestObj {
    #[serde(default = "TestObj::get_default_field1")]
    pub field1: bool,
    #[serde(default = "TestObj::get_default_field2")]
    pub field2: u64,
    #[serde(default = "TestObj::get_default_field3")]
    pub field3: String,
}

impl TestObj {

    pub fn get_default_field1() -> bool {
        true
    }

    pub fn get_default_field2() -> u64 {
        100u64
    }

    pub fn get_default_field3() -> String {
        String::from("test_str")
    }

}

can be simplified to:

#[derive(Deserialize, DefaultFields)]
struct TestObj {
    #[serde(default = "TestObj::get_default_field1")]
    pub field1: bool,
    #[serde(default = "TestObj::get_default_field2")]
    pub field2: u64,
    #[serde(default = "TestObj::get_default_field3")]
    pub field3: String,
}

impl Default for TestObj {
    fn default -> Self {
        Self {
            field1: true,
            field2: 100u64,
            field3: String::from("test_str"),
        }
    }
}

Dependencies

~220–660KB
~16K SLoC