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

Using schema_with with a generic function #375

Open
hniksic opened this issue Feb 19, 2025 · 0 comments
Open

Using schema_with with a generic function #375

hniksic opened this issue Feb 19, 2025 · 0 comments

Comments

@hniksic
Copy link

hniksic commented Feb 19, 2025

This fails to compile:

#[derive(JsonSchema)]
struct Helper<T> {
    #[schemars(schema_with = "json_schema::<T>")]
    props: T,
}

fn json_schema<T>(gen: &mut schemars::gen::SchemaGenerator) -> Schema {
    todo!() // will use `T::json_schema()` and possibly other things from `T`
}

The error is:

275 |             struct Helper<T> {
    |                           - type parameter from outer item
276 |                 #[schemars(schema_with = "json_schema::<T>")]
    |                                          ^^^^^^^^^^^^^^^^^^- help: try introducing a local generic parameter here: `<T>`
    |                                          |
    |                                          use of generic parameter from outer item

However, equivalent serde annotation works with generics. For example, this compiles just fine:

#[derive(Deserialize)]
struct Foo<T> {
    #[serde(deserialize_with = "my_deserializer::<'de, T, _>")]
    foo: u32,
    bla: T,
}

fn my_deserializer<'de, T, D: Deserializer<'de>>(data: D) -> Result<u32, D::Error> {
    todo!()
}

Is it possible to use schema_with with a generic function? My use case is adding additional information to the schema generated by T::json_schema() of a generic T parameter in a struct.

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

No branches or pull requests

1 participant