Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static defaults for Serde

Tags:

rust

serde

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.

like image 491
Yuri Gor Avatar asked Jul 03 '26 09:07

Yuri Gor


1 Answers

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

like image 151
Oussama Gammoudi Avatar answered Jul 06 '26 03:07

Oussama Gammoudi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!