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()),
};
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");
Edit 2025-02-17: I added the get_default_serde_record
function to the serde-aux
crate, so this is now more convenient. See PR: https://github.com/iddm/serde-aux/pull/40