From b38a55331b8b6171305359f618e997a7ce275e4d Mon Sep 17 00:00:00 2001 From: Graeme Coupar Date: Mon, 24 May 2021 16:51:26 +0100 Subject: [PATCH] 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. --- schemars/tests/default.rs | 11 +++++++++++ schemars/tests/expected/generic_default.json | 14 ++++++++++++++ schemars_derive/src/schema_exprs.rs | 2 +- 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 schemars/tests/expected/generic_default.json diff --git a/schemars/tests/default.rs b/schemars/tests/default.rs index 0d68d0e..4623994 100644 --- a/schemars/tests/default.rs +++ b/schemars/tests/default.rs @@ -54,3 +54,14 @@ pub struct NotSerialize; fn schema_default_values() -> TestResult { test_default_generated_schema::("default") } + +#[derive(Default, Deserialize, Serialize, JsonSchema, Debug, PartialEq)] +pub struct StructWithGenericDefaults { + #[serde(default = "Vec::new")] + pub a_vec: Vec, +} + +#[test] +fn schema_with_generic_default_value() -> TestResult { + test_default_generated_schema::("generic_default") +} diff --git a/schemars/tests/expected/generic_default.json b/schemars/tests/expected/generic_default.json new file mode 100644 index 0000000..095b999 --- /dev/null +++ b/schemars/tests/expected/generic_default.json @@ -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" + } + } + } +} \ No newline at end of file diff --git a/schemars_derive/src/schema_exprs.rs b/schemars_derive/src/schema_exprs.rs index c5b1672..6efa9b8 100644 --- a/schemars_derive/src/schema_exprs.rs +++ b/schemars_derive/src/schema_exprs.rs @@ -581,7 +581,7 @@ fn field_default_expr(field: &Field, container_has_default: bool) -> Option quote!(<#ty>::default()), - SerdeDefault::Path(path) => quote!(#path()), + SerdeDefault::Path(path) => quote!(|| -> #ty { #path() }()), }; let default_expr = match field.serde_attrs.skip_serializing_if() {