rust
32 lines · 6 steps
Tagged enums with serde in Rust
A single enum models several JSON event shapes using serde's internally tagged representation.
Explained by
highlit
1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Serialize, Deserialize)]
4#[serde(tag = "type", rename_all = "snake_case")]
5pub enum Event {
6 PageView {
7 url: String,
8 #[serde(default)]
9 referrer: Option<String>,
10 },
11 Click {
12 url: String,
13 element_id: String,
14 #[serde(default)]
15 x: u32,
16 #[serde(default)]
17 y: u32,
18 },
19 FormSubmit {
20 form_id: String,
21 fields: std::collections::HashMap<String, String>,
22 },
23 Custom {
24 name: String,
25 #[serde(default)]
26 payload: serde_json::Value,
27 },
28}
29
30pub fn parse_events(raw: &str) -> Result<Vec<Event>, serde_json::Error> {
31 serde_json::from_str(raw)
32}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1An internally tagged enum lets one type round-trip several distinct JSON shapes selected by a discriminator field.
- 2serde attributes like default and rename_all shape the wire format without changing your Rust field names.
- 3Deserializing directly into a domain enum turns runtime JSON validation into compile-time exhaustiveness.
Related explainers
python
from flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
rust
use axum::{ extract::State, routing::{get, post, MethodRouter}, Json, Router,
Self-documenting routes in Axum
builder-pattern
closures
shared-state
Intermediate
8 steps
rust
use std::collections::HashMap; use std::fs::File; use std::io::{self, BufRead, BufReader}; use std::path::Path;
Parsing INI files in Rust
parsing
file-io
hashmap
Intermediate
9 steps
rust
use axum::{ extract::{Path, Query}, http::Uri, response::{IntoResponse, Redirect},
Building HTTP redirect handlers in Axum
redirects
extractors
url-handling
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/tagged-enums-with-serde-in-rust-explained-rust-f049/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.