Support generic default values

I'm trying to `derive(JsonSchema)` on a field with a default that relies
on type inference to determine it's return type.  This causes compile
errors because schemars calls the default function without providing
any types for inference to use.

This changes that - wraps the `default` in a closure with a defined
return value that it immediately calls.  Feels a bit hacky, but I
couldn't think of a better way to fix this.
This commit is contained in:
Graeme Coupar 2021-05-24 16:51:26 +01:00 committed by Graham Esau
parent e9d5f4057e
commit b38a55331b
3 changed files with 26 additions and 1 deletions

View file

@ -54,3 +54,14 @@ pub struct NotSerialize;
fn schema_default_values() -> TestResult {
test_default_generated_schema::<MyStruct>("default")
}
#[derive(Default, Deserialize, Serialize, JsonSchema, Debug, PartialEq)]
pub struct StructWithGenericDefaults {
#[serde(default = "Vec::new")]
pub a_vec: Vec<String>,
}
#[test]
fn schema_with_generic_default_value() -> TestResult {
test_default_generated_schema::<StructWithGenericDefaults>("generic_default")
}

View file

@ -0,0 +1,14 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "StructWithGenericDefaults",
"type": "object",
"properties": {
"a_vec": {
"default": [],
"type": "array",
"items": {
"type": "string"
}
}
}
}

View file

@ -581,7 +581,7 @@ fn field_default_expr(field: &Field, container_has_default: bool) -> Option<Toke
quote!(container_default.#member)
}
SerdeDefault::Default => quote!(<#ty>::default()),
SerdeDefault::Path(path) => quote!(#path()),
SerdeDefault::Path(path) => quote!(|| -> #ty { #path() }()),
};
let default_expr = match field.serde_attrs.skip_serializing_if() {