serde icon indicating copy to clipboard operation
serde copied to clipboard

Add skip_serializing_if_default field attribute

Open Gordon01 opened this issue 3 years ago • 3 comments

This attribute skips field serialization if its value equals default.

Motivation:

Imagine we have an application, where the config may be changed dynamically and needs to be saved. Or just be saved for some reason.

#[derive(Serialize, Deserialize, Debug)]
struct Config {
    #[serde(default = "default_version")]
    version: u32,
    #[serde(default = "default_author")]
    author: String,
}

Probably we have a lot of fields that just defaulted and saving them will add unnecessary noise to the config file.

We may use skip_serializing_if attribute and provide functions that check if the value is default:

#[derive(Serialize, Deserialize, Debug)]
struct Config {
   #[serde(default = "default_version", skip_serializing_if = "is_version_default")]
   version: u32,
   #[serde(default = "default_author", skip_serializing_if = "is_author_default")]
   author: String,
}

fn is_version_default(value: &u32) -> bool {
   *value == default_version()
}

fn is_author_default(value: &String) -> bool {
   *value == default_author()
}

This adds lots of one-line functions and noise to the code.

Solution:

Use skip_serializing_if_default attribute from this PR:

#[derive(Serialize, Deserialize, Debug)]
struct Config {
    #[serde(default = "default_version", skip_serializing_if_default)]
    version: u32,
    #[serde(default = "default_author", skip_serializing_if_default)]
    author: String,
}

It calls the field's default function, compares its current value, and if it matches with the value provided by the default function, skips serialization.

Gordon01 avatar Apr 27 '22 21:04 Gordon01

I've added a test for this feature and fixed the wrong struct length that was revealed by the test. I don't like the code duplication, but it seems to me it's the style you prefer.

Any advice on how it should be?

Otherwise, the feature seems to be complete.

Gordon01 avatar May 12 '22 21:05 Gordon01