1

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.

#[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;
}
cafce25
  • 15,907
  • 4
  • 25
  • 31
Marco
  • 61
  • 7

1 Answers1

3

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

cafce25
  • 15,907
  • 4
  • 25
  • 31
  • Thank you very much. If possible, could you elaborate more "That's not how skip_serializing_if works or what it's for" please? – Marco Jul 29 '23 at 10:27
  • Well with the interface it provides and global variables generally being frowned upon, it's not that difficult to see that the main use case for it is skipping serialization of default values for a field. – cafce25 Jul 29 '23 at 12:36