typestar

Enums and tagging in Rust

How an enum crosses the wire: internally tagged, untagged, or as a bare string.

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
enum Event {
    Start { lang: String },
    Finish { tpm: u32, stars: u8 },
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum Theme {
    Default,
    Monokai,
}

fn main() -> Result<(), serde_json::Error> {
    let events = vec![
        Event::Start { lang: "rust".to_string() },
        Event::Finish { tpm: 104, stars: 3 },
    ];
    println!("{}", serde_json::to_string(&events)?);
    println!("{}", serde_json::to_string(&Theme::Monokai)?);
    Ok(())
}

How it works

  1. A tag attribute writes the variant name into a field.
  2. untagged matches on shape instead of a tag.
  3. A unit-variant enum serializes as a plain string.

Keywords and builtins used here

The run, in numbers

Lines
25
Characters to type
572
Tokens
154
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 88 seconds.

Type this snippet

Step 2 of 2 in Shapes, step 8 of 11 in Serde & JSON.

← Previous Next →