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

Example of gotcha with internally tagged enums and child structs #170

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions _src/enum-representations.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,39 @@ structs or maps, and unit variants but does not work for enums containing tuple
variants. Using a `#[serde(tag = "...")]` attribute on an enum containing a
tuple variant is an error at compile time.

Note that when using struct variants, a common mistake is to include the tag field in the child structs. This will cause a runtime error, because the tag field is not available to the parser of the child struct.

As an example, this code will work correctly, but if you un-comment the `pet` fields, it will fail at runtime:

```
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(tag = "pet")]
enum CompanionAnimal {
Cat(CatInfo),
Dog(DogInfo),
}

#[derive(Debug, Deserialize)]
struct CatInfo {
//pet: String,
sound: String,
}

#[derive(Debug, Deserialize)]
struct DogInfo {
//pet: String,
sound: String,
}

fn main() {
let data = r#" { "pet": "Cat", "sound": "meow" } "#;
let parsed = serde_json::from_str::<CompanionAnimal>(data).unwrap();
dbg!(&parsed);
}
```

## Adjacently tagged

```rust
Expand Down