Sub topic 8
Choosing an enum representation
This chapter assumes you can derive Serialize and Deserialize, use serde_json, and read container attributes such as rename_all. Here you will choose how serde writes an enum as JSON.
Why enums need a decision
A struct maps naturally to a JSON object. An enum is different, because the JSON must also record which variant it holds. Serde offers four ways to do that. The choice changes the JSON shape, so it usually follows from the format you must read or write.
The four representations
| Representation | Attribute | Shape of `Click { x: 1, y: 2 }` |
|---|---|---|
| Externally tagged | none (default) | `{"Click":{"x":1,"y":2}}` |
| Internally tagged | `tag = "type"` | `{"type":"Click","x":1,"y":2}` |
| Adjacently tagged | `tag = "t", content = "c"` | `{"t":"Click","c":{"x":1,"y":2}}` |
| Untagged | `untagged` | `{"x":1,"y":2}` |
A unit variant such as Quit is the plain string "Quit" when externally tagged. With the other tagged forms it becomes an object holding only the tag.
Seeing all four
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
enum External {
Click { x: i32, y: i32 },
Quit,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
enum Internal {
Click { x: i32, y: i32 },
Quit,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "t", content = "c")]
enum Adjacent {
Click { x: i32, y: i32 },
Quit,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
enum Id {
Num(u64),
Text(String),
}
fn main() -> Result<(), serde_json::Error> {
println!("{}", serde_json::to_string(&External::Click { x: 1, y: 2 })?);
// {"Click":{"x":1,"y":2}}
println!("{}", serde_json::to_string(&External::Quit)?);
// "Quit"
println!("{}", serde_json::to_string(&Internal::Click { x: 1, y: 2 })?);
// {"type":"Click","x":1,"y":2}
println!("{}", serde_json::to_string(&Adjacent::Click { x: 1, y: 2 })?);
// {"t":"Click","c":{"x":1,"y":2}}
let a: Id = serde_json::from_str("42")?;
let b: Id = serde_json::from_str(r#""abc""#)?;
println!("{a:?} {b:?}"); // Num(42) Text("abc")
Ok(())
}How to choose
- Externally tagged is the default and works with every variant kind. Pick it when you control both ends.
- Internally tagged matches APIs that put a
"type"field inside the object. It reads well, but it only works for struct variants, unit variants, and newtype variants that wrap a struct or map. - Adjacently tagged handles payloads that internal tagging cannot, such as tuple variants, at the cost of extra nesting.
- Untagged fits data where the values differ in shape, like
Idabove.
Gotchas
Internal tagging with an unsupported variant shape compiles, but fails when you serialize or deserialize. Test every variant with a round trip. Combine rename_all with the tag to control the variant names written, for example #[serde(tag = "type", rename_all = "snake_case")].
Exercise
An API sends {"kind":"circle","radius":2.0} and {"kind":"square","side":3.0}. Which representation and attributes should the Shape enum use, and what variant names does it need?
Show answer
Use internal tagging: #[serde(tag = "kind", rename_all = "snake_case")]. Declare struct variants Circle { radius: f64 } and Square { side: f64 }. The snake_case renaming turns them into "circle" and "square".