Function get_default_serde_record

Source
pub fn get_default_serde_record<'de, T>() -> Result<T, Error>
where T: Deserialize<'de>,
Expand description

Get the default record for a struct implementing the serde::Deserialize trait.

This helper function is useful in particular when the #[serde(default = "path")] field attribute is used to customize the default record definition, as it avoids the need to implement the Default trait manually for the defined struct, paying attention to keep it aligned with Serde’s attributes configuration.

§Example

use serde_aux::prelude::*;

#[derive(serde::Deserialize, PartialEq, Debug)]
struct Record {
    #[serde(default = "default_string")]
    label: String,
    #[serde(default = "default_f64")]
    value1: f64,
    #[serde(default)]
    value2: f64,
    #[serde(skip)]
    foo: bool,
}

fn default_string() -> String {
    String::from("default")
}

fn default_f64() -> f64 {
    1.0
}

let empty_record = get_default_serde_record::<Record>().unwrap();
assert_eq!(
    empty_record,
    Record {
        label: String::from("default"),
        value1: 1.0,
        value2: 0.0,
        foo: false
    }
);