I am working on my data models (mongodb->serde) And in the SerDe docs I found that to specify defaults for some fields I need to give function name (path).
But In my case I have trivial static defaults, I don't need to assign them dynamically, so code I wrote looks redundant:
fn zero() -> i32 {
0
}
fn yes() -> bool {
true
}
fn no() -> bool {
false
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Relation {
#[serde(rename = "_id")]
pub id: oid::ObjectId,
#[serde(default = "no")]
pub side_effect: bool,
#[serde(default = "yes")]
pub positive: bool,
#[serde(default = "no")]
pub negative: bool,
#[serde(default = "zero")]
pub duration: i32,
}
Is there any better way without declaring all these helper functions? Ideally I'd prefer to provide static value right in field attribute, or maybe there is some create with already defined most common default functions? And is it possible at least to provide argument to such default function, so I could write one function per type and it will just return provided argument.
You can use #[serde(default)] for 0 , false, empty String, empty Vector or for any struct that implements the Default trait.
So in your case you will only need the yes function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With