Search code examples
rustserde

How to get the default instance of a Serde struct


Let's consider the following sample code (my actual code have several tenths of fields):

fn empty_field() -> Result<f64, String> {
    Err(String::new())
}

#[derive(Deserialize, Serialize)]
struct Record {
    #[serde(rename = "Apple", default)]
    a: f64,
    #[serde(rename = "Banana", default)]
    b: String,
    #[serde(rename = "Coconut", default = "empty_field")]
    c: Result<f64, String>,
}

Is it possible to get the the default instance based on Serde annotations, without defining it manually as follows?

let empty_record = Record {
    a: 0.0,
    b: String::new(),
    c: Err(String::new()),
};

Solution

  • Thanks @BallpointBen and @cdhowie, this is my final implementation:

    let empty_data = std::iter::empty::<((), ())>();
    let empty_deserializer =
        serde::de::value::MapDeserializer::<_, serde::de::value::Error>::new(empty_data);
    let empty_record =
        Record::deserialize(empty_deserializer).expect("empty record should deserialize correctly");