Sub topic 1
What serde does and how it is organized
Prerequisites
This chapter assumes you know Rust structs, enums, traits, and generics. You should be able to add a dependency with Cargo and handle a Result with the ? operator. You should also know what JSON looks like. Lifetimes matter only in a later chapter.
The problem serde solves
Programs often need to turn a value in memory into bytes, or the reverse. Examples are writing a config file, calling a web API, or saving a cache. Each data format, such as JSON, TOML, or MessagePack, has its own syntax. Writing one converter per type per format would multiply the work: with M types and N formats, you would write M × N converters.
serde removes that multiplication. The name is short for serialize and deserialize. Your types describe themselves once. Each format crate describes how to read and write its own syntax once. serde connects the two sides.
How serde is organized
serde is split into separate crates, each with one job.
| Piece | Role |
|---|---|
| `serde` | The core traits `Serialize` and `Deserialize`, plus the data model |
| `serde_derive` | Derive macros that generate the trait implementations. You enable it with the `derive` feature of `serde`. |
| Format crates such as `serde_json` or `toml` | Read and write one format each |
A format crate does not know about your types. Your types do not know about any format. Both sides only know the serde data model, which is a fixed set of types such as integers, strings, sequences, maps, and structs. A later chapter covers the data model in detail.
Because of this design, adding a new format crate gives every existing serde type support for that format. Adding Serialize to a type gives it support for every format.
A first example
Add the dependencies to Cargo.toml:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"Then derive both traits on a struct and convert it to JSON and back:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct User {
id: u32,
name: String,
email: Option<String>,
}
fn main() -> Result<(), serde_json::Error> {
let user = User {
id: 1,
name: "Ada".to_string(),
email: None,
};
let json = serde_json::to_string(&user)?;
println!("{json}"); // {"id":1,"name":"Ada","email":null}
let back: User = serde_json::from_str(&json)?;
println!("{back:?}");
Ok(())
}The derive lines generate the code that describes User to serde. serde_json::to_string is the JSON side of the bridge. None becomes null, which shows the data model at work: serde has a concept of an optional value, and each format chooses how to write it.
Common mistakes
- Missing
derivefeature. If you write#[derive(Serialize)]and get an error that the macro cannot be found, thederivefeature is not enabled onserde. - Forgetting the format crate.
serdealone cannot produce JSON. You also needserde_json. - Missing trait import. Derive macros need
use serde::{Serialize, Deserialize};in scope. - Fields without support. Every field type must itself implement the trait. A field whose type lacks
Serializemakes the derive fail to compile.
Exercise
Your project has 5 types and needs to support 3 formats. How many converters would you write by hand without serde's design, and what do you write with serde?
Show answer
Without serde's design you would write 5 × 3 = 15 converters. With serde, each type derives or implements Serialize and Deserialize once (5 pieces of code, usually derives), and each format has one crate that talks to the data model (3 crates, which already exist for common formats).
Exercise
You add #[derive(Serialize)] to a struct and the compiler reports that it cannot find the derive macro. What is the most likely cause?
Show answer
The derive feature is not enabled for the serde dependency. Use serde = { version = "1", features = ["derive"] }.