schemars icon indicating copy to clipboard operation
schemars copied to clipboard

non-Serialize defaults are silently ignored

Open ahl opened this issue 3 years ago • 2 comments

The fix for #115 made it so that the #[serde(default)] annotation doesn't generate a build error when the type of the field to which the annotation is applied is not Serialize. This is completely fine for types that have a well-understood default value, for example arrays/Vecs as []. In other cases--such as the one below--the default value is simply ignored:

#[derive(serde::Deserialize, schemars::JsonSchema)]
struct Outer {
    #[serde(default)]
    field: Inner,
}

#[derive(serde::Deserialize, schemars::JsonSchema, Default)]
struct Inner {
    a: bool,
}

In cases such as this, it might be beneficial to have an error to indicate that the default value is ignored.

For types such as Vec<T> where the serialization of the default value is independent of whether T is or is not Serialize it might be helpful to still emit that default value ([]).

Another option to consider might be to have a #[schemars(default = "path")] override that expects path to be a fn () -> serde_json::Value (rather than fn () -> T. This would let consumers specify a default value without going through the intermediate step and then serializing it.

ahl avatar Apr 27 '22 21:04 ahl

This is intentional - adding #[derive(JsonSchema)] to types that do not implement Serialize (like in your example) is a valid use-case.

I would be open to making #[schemars(default)] error if the default value can't be serialized, but I think if the default value comes from a serde attribute then schemars should not error when the default value can't be serialized.

GREsau avatar Aug 13 '24 19:08 GREsau

Having #[schemars(default)] produce an error seems sensible. What do you think about including some information in the docs about #[serde(default)] being ignored if the type isn't Serialize?

ahl avatar Aug 14 '24 15:08 ahl