serde-rs / serde

Serialization framework for Rust
https://serde.rs/
Apache License 2.0
8.81k stars 747 forks source link

Expanded #[serder(default = ...)] capabilities. #2728

Open Threadzless opened 2 months ago

Threadzless commented 2 months ago

Before

Giving a field a default value that isn't the same as that type's Default required users to define a function for each field.

#[derive(Serialize, Deserialize)]
pub struct MyStruct {
    #[serde(default = "my_struct_a_default")]
    a: i32,
    #[serde(default = "my_struct_b_default")]
    b: i32,
}

fn my_struct_a_default() -> i32 {
    12
}
fn my_struct_b_default() -> i32 {
    16
}

Now

Constant expressions may also be used, so long as they are wrapped in parenthesis

#[derive(Serialize, Deserialize)]
pub struct MyStruct {
    #[serde(default = (12))]
    a: i32,
    #[serde(default = (16))]
    b: i32,
}

The requirement of wrapping expressions in parenthesis is to ensure string values are not mistaken for a path to a function. This ensures full backwards compatibility.

I have also modified some of the tests to verify this new capability, and incremented the version number

Threadzless commented 1 week ago

updated to match latest version