serde
serde copied to clipboard
How to enforce a single enum variant with flatten
At the moment, I can't find a way to enforce that only a single variant of an enum is set for a field when using #[serde(flatten)]. I would expect that if I had a setup like this:
#[derive(Debug, Deserialize)]
enum MultipleOptions {
FirstThing(HashMap<String, String>),
SecondThing(HashMap<String, String>),
}
#[derive(Debug, Deserialize)]
struct AThing {
#[serde(flatten)]
multiple_options: MultipleOptions
}
Then JSON like this:
{"FirstThing": {}, "SecondThing": {}}
Would be an error when deserializing AThing (as it is when deserializing MultipleOptions). I assume this is because it's treating the second variant it encounters like an unknown field.
Adding #[serde(deny_unknown_fields)] to AThing solves this problem:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4088008fef23f3d7b4eca16aebca5e15