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?
question from:
https://stackoverflow.com/questions/65844153/serde-use-container-serdedefault-but-with-some-required-fields 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…