serde-rs / serde

Serialization framework for Rust
https://serde.rs/
Apache License 2.0
8.81k stars 747 forks source link

Trait bounds for deserialization are enforced even if deserialization is skipped. #2736

Open SetOfAllSets opened 2 months ago

SetOfAllSets commented 2 months ago

In the example

#[derive(Deserialize)]
struct SomeStruct {
    something: String,
    #[serde(skip_deserializing)]
    SomethingElse: String,
    AThirdThing: &String,
}

the AThirdThing field causes the error the trait bound `&std::string::String: Deserialize<'_>` is not satisfied despite the fact that it is not being deserialized.

jonasbb commented 2 months ago

In the shared code snippet, you only skip deserialization of the second SomethingElse field, not the third AThirdThing. To achieve that, you need to annotate that field as well (I fixed the Rust code too):

#[derive(Deserialize)]
struct SomeStruct<'a> {
    something: String,
    #[serde(skip_deserializing)]
    SomethingElse: String,
    #[serde(skip_deserializing)]
    AThirdThing: &'a String,
}

However, that still won't quite work, since &'a String does not implement Default, see https://serde.rs/field-attrs.html#skip_deserializing. You need to specify a default = "..." as well, to tell the deserialization code how the field value should get created, since it doesn't come from the serialized data.