Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow example attribute value to be any expression #354

Merged
merged 2 commits into from
Nov 20, 2024
Merged

Conversation

GREsau
Copy link
Owner

@GREsau GREsau commented Nov 20, 2024

#[schemars(example = 0.1)]
n: f32,
#[schemars(example = "example value", example = a_second_example())]
s: String,

Currently, the example attribute mirrors serde's default 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:

#[derive(JsonSchema)]
pub struct MyStruct {
    #[schemars(example = "foo")]
    pub my_int: i32,
}

fn foo() -> i32 {
   123
}

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 function example().

@GREsau GREsau merged commit e516881 into master Nov 20, 2024
8 checks passed
@GREsau GREsau deleted the example-attr-expr branch November 20, 2024 22:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant