Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Skip serializing at runtime with `skip_serializing_if`?

I read about serde::skip_serializing_if and I would like to iplement it into my project, however I did not find a way to read the value at runtime (imagine a flag --ignore-practices).

I tried with a static value but without success…

See example below.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct IP {
    pub name: String,
    #[serde(skip_serializing_if = "read_flag_from_command_line")]
    pub practices: Option<Practices>,
}

fn is_false<T>(_: T) -> bool {
    let ignore = value_at_run_time;
    return ignore;
}

>Solution :

That’s not how skip_serializing_if works or what it’s for, the function given to it has to take the field as a reference and should determine it’s result based on that.

That being said you could write a function that depends on global state to determine if it serializes or not as a hack:

static SERIALIZE_PRACTICES: AtomicBool = AtomicBool::new(false);

fn dont_serialize_practices<T>(_: &T) -> bool {
    !SERIALIZE_PRACTICES.load(Ordering::Acquire)
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Ip {
    #[serde(skip_serializing_if = "dont_serialize_practices")]
    pub practices: Option<String>,
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading