serde icon indicating copy to clipboard operation
serde copied to clipboard

How to enforce a single enum variant with flatten

Open dbanty opened this issue 2 years ago • 1 comments

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.

Here's a playground that demonstrates this fully

dbanty avatar Jul 21 '23 17:07 dbanty

Adding #[serde(deny_unknown_fields)] to AThing solves this problem:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4088008fef23f3d7b4eca16aebca5e15

Mingun avatar Aug 03 '24 11:08 Mingun