I have a struct that uses the #[serde(default)] container attribute.
But there is one field that should be required (if this field doesn't exist in the incoming data, the deserializer should error out instead of falling back to default value).
#[serde(default)]
#[derive(Serialize, Deserialize)]
struct Example {
important: i32, // <-- I want this field to be required.
a: i32, // <-- If this field isn't in the incoming data, fallback to the default value.
b: i32, // <-- If this field isn't in the incoming data, fallback to the default value.
c: i32, // <-- If this field isn't in the incoming data, fallback to the default value.
}
Edit:
The information below isn't correct. The #[serde(default)] field attribute does not take the default value of the struct type, but rather of each field's type. (i.e. impl Default for Example isn't used. impl Default for i32 is used).
End Edit.
I could use the #[serde(default)] field attribute like this:
#[derive(Serialize, Deserialize)]
struct Example {
important: i32,
#[serde(default)]
a: i32,
#[serde(default)]
b: i32,
#[serde(default)]
c: i32,
}
So important would be required, while a, b, and c would have default values.
But copy-pasting #[serde(default)] for all but one field doesn't seem like a good solution (my struct has ~10 fields).
Is there a better way?
importantandbare specified e.g. the following JSON{ "important": 1, "b": 2 }. Shouldaandcstill be default. If yes, then repeating it 10 times, might be the shortest solution. Edit: I was about to suggest using a second struct andserde(default)+serde(flatten)but that doesn't seem to be supported (see issue #1626) - vallentinimportantandb,aandcshould be default. Your suggestion to useserde(flatten)would require an additional layer when accessing the fields, likeexample.data.a. I've decided to just copy paste ten times. - wishaserde(default)+serde(flatten)is currently unsupported, then yeah, the most straightforward solution is just to useserde(default)x10 - vallentin