Skip to content

Infer Default bound automatically #475

@nkovacs

Description

@nkovacs

This does not compile:

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, JsonSchema)]
struct Foo<T> {
    #[serde(default)]
    foo: T,
}

The generated code contains <T>::default, generated here:

SerdeDefault::Default => quote!(<#ty>::default()),

but it doesn't add T: Default into the where clause, so the code doesn't compile.

Serde's Deserialize derive adds a T: Default bound automatically (so Foo can only be deserialized if T is Default). Schemars should do the same.

Manually adding the bound fixes it, of course:

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, JsonSchema)]
#[schemars(bound = "T: JsonSchema + Default")]
struct Foo<T> {
    #[serde(default)]
    foo: T,
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions