Allow example
attribute value to be any expression
#354
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Currently, the
example
attribute mirrors serde'sdefault
attribute, in that its value must be a string literal identifying a function to call. This requires consumers to define a function that usually just returns a constant value, which is really just boilerplate. "Default literals" is a popular feature request for serde (serde-rs/serde#368), although it's a bit awkward to implement cleanly due to backward-compatibility.But unlike serde, schemars is still in pre-v1, so it's easier to making occasional breaking changes, and this is a case where I'd rather cause an up-front breaking change to avoid a long-term API wart.
While I'm comfortable making this a breaking change, I'm concerned with the ambiguity that would arise from naively updating schemars from 0.8.x (or <v1.0.0-alpha.15) when using
example
- e.g. consider existing code:This currently sets the
examples
schema property to[123]
, but with the new behaviour, would still compile and run, but set the property to["foo"]
. There would be no clear indication that they would need to change the attribute to either#[schemars(example = foo())]
or#[schemars(example = 123)]
.Because of that, I think the safest way to make this change is to disallow string literals that contain a value parseable as a function path, which will cause a compile error until the attribute is updated. If you do want to set the example value to a such a string, then a simple workaround would be to borrow the string, e.g.
#[schemars(example = &"example")]
which would unambiguously refer to the string value instead of a functionexample()
.