default_fields

Crates.iodefault_fields
lib.rsdefault_fields
version0.1.0
sourcesrc
created_at2024-10-08 03:04:09.961342
updated_at2024-10-08 03:04:09.961342
descriptionA simple derive macro that adds a default getter function for each struct field
homepage
repositoryhttps://github.com/qusuyan/DefaultFields.git
max_upload_size
id1400731
size5,480
Suyan Qu (qusuyan)

documentation

README

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"),
        }
    }
}
Commit count: 11

cargo fmt