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
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 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.