Sub topic 1
What serde does and how it is organized
serde is the standard Rust framework for converting data structures to and from other representations, such as JSON, TOML, or a compact binary format. This chapter explains the problem serde solves, how its crates divide the work, and what happens at compile time when you use it. Later chapters cover each piece in detail.
Prerequisites
This chapter assumes you already know:
- Rust basics: structs, enums, traits, generics, and lifetimes.
- How to use Cargo and add dependencies, including feature flags.
- How to handle
Resultand use the?operator. - What JSON looks like: objects, arrays, strings, numbers, booleans, and
null.
You do not need to know how macros or procedural macros work internally.
The problem serde solves
Programs often need to turn an in-memory value into bytes or text, and back. You might write a config file, call a web API, or store records on disk. Done by hand, this means writing a converter for each type and each format.
Suppose you have M data types and N formats. Writing every converter yourself takes M × N pieces of code. Each new type needs work for every format, and each new format needs work for every type.
serde reduces this to M + N. Each type describes itself once, in terms of a shared vocabulary. Each format learns that vocabulary once. Any type then works with any format.
The shared vocabulary is called the data model. It is a fixed set of about 29 kinds of value, such as integers, strings, sequences, maps, structs, and enum variants. The next chapter covers it in detail. For now, treat it as a neutral middle layer that sits between your types and a format.
Two sides, two traits
serde splits the work between two sides, and each side has a trait.
- Data structures implement
SerializeandDeserialize. A type that implementsSerializeknows how to describe itself using the data model. A type that implementsDeserializeknows how to build itself from data-model values. - Data formats implement
SerializerandDeserializer. ASerializerknows how to write data-model values in one format. ADeserializerknows how to read that format and report what it finds as data-model values.
Neither side knows about the other. A Serialize type never mentions JSON, and a JSON Serializer never mentions your struct. They meet only through the data model.
How the crates are organized
serde is a family of crates rather than one library. Knowing which crate provides what saves time when you read documentation or debug a build.
| Crate | Role |
|---|---|
| `serde` | The traits (`Serialize`, `Deserialize`, `Serializer`, `Deserializer`), the data model, and implementations for standard library types |
| `serde_derive` | The procedural macros behind `#[derive(Serialize, Deserialize)]`. You normally do not depend on it directly |
| `serde_json` | A format crate for JSON |
| `toml`, `csv`, `bincode`, `rmp-serde`, and others | Other format crates. Each implements `Serializer` and `Deserializer` |
The serde crate re-exports the derive macros, but only when you turn on its derive feature. This is why most projects declare the dependency like this:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"Without features = ["derive"], use serde::Serialize; still imports the trait, but #[derive(Serialize)] fails to compile because the macro is not available.
The split matters when you choose dependencies. A library that defines public types usually depends only on serde, so it stays independent of any format. An application picks the format crates it needs.
A first round trip
This program shows all three parts working together. The derive macros supply the trait implementations, and serde_json supplies the format.
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:?}"); // User { id: 1, name: "Ada", email: None }
Ok(())
}Four things in this program show how serde is organized:
Usernever mentions JSON. It only derives the two traits.serde_json::to_stringis generic overT: Serialize. It accepts any serializable type, not justUser.serde_json::from_stris generic overT: Deserialize. The annotationlet back: Usertells it which type to build.Nonebecomes JSONnull. The data model has an "option" concept, and JSON's serializer choosesnullas its spelling of "none".
What the derive does at compile time
#[derive(Serialize, Deserialize)] runs during compilation and generates ordinary Rust code. For User, it writes an impl Serialize for User that announces a struct named User with three fields and then hands over each field in order. It also writes an impl Deserialize that knows how to accept those fields and assemble a User.
This design has several consequences:
- No runtime reflection. Rust cannot inspect a struct's fields at run time, so serde does not try. All the field knowledge is baked into generated code before the program runs.
- Static dispatch. The trait methods are generic over the
Serializer. The compiler produces a specialized copy for each type and format pair, which usually makes serialization about as fast as hand-written code. The cost is longer compile times and larger binaries when you use many types with many formats. - No intermediate tree by default. Serialization streams values straight from your struct to the output. serde does not build a generic document in memory first. (You can opt into one with
serde_json::Value, covered later.) - Every field must be serializable. If a struct has a field whose type does not implement
Serialize, the derive fails to compile with a "trait bound not satisfied" error that points at that type.
Types from other crates
serde implements its traits for the standard library types: integers, String, Vec<T>, HashMap<K, V>, Option<T>, tuples, and many more. For types from other crates, the implementation must come from somewhere. Rust's orphan rule prevents you from writing impl Serialize for chrono::DateTime<Utc> in your own crate, because both the trait and the type are foreign.
The usual solution is that the owning crate provides the implementation behind a feature flag, often named serde. For example, a crate might document chrono = { version = "0.4", features = ["serde"] }. When a build fails because a third-party type lacks Serialize, check that crate's features first.
What serde does not do
serde has clear limits, and knowing them prevents wrong assumptions.
- It does not parse or print text itself. Tokenizing JSON and writing it back is the format crate's job. serde only defines the interface.
- It does not guarantee that every type works with every format. The data model is wide, but formats are narrower. JSON object keys must be strings, so serializing a
HashMap<Vec<u8>, i32>to JSON fails at run time with an error, not at compile time. Likewise, TOML has nonull, soNoneneeds special handling there. - It does not guarantee a lossless round trip. If a type serializes in a lossy way, such as a set written as a list, the value you read back may not equal the one you wrote. Formats also differ in numeric range and precision.
- It is not a schema language. The shape of the data is whatever your Rust types and attributes produce. serde does not validate against an external schema.
Where the rest of the tutorial goes
The following chapters build on this layout in a rough order. First comes the data model and the two traits. After that, the derive macros and serde_json get a full treatment, along with attributes that reshape output. Then come enum representations, error handling, and other formats. The last chapters cover untyped values, custom field logic, hand-written implementations, borrowed deserialization, and the Deserializer and Visitor machinery behind Deserialize.
Exercise
You are writing a library crate that defines public structs for an API's request and response bodies. Your application will use JSON today, and the team may add TOML or a binary format later. Which serde-related dependencies should the library declare, and why?
Show answer
The library should depend on serde with the derive feature and should not depend on serde_json or any other format crate. Its types only need to implement Serialize and Deserialize, which are format-neutral. The application picks serde_json now and can add toml or bincode later without any change to the library. Adding a format crate to the library would force every user to compile it and tie the library to that format.
Exercise
A #[derive(Serialize)] on your struct fails to compile. The error says a field of type chrono::NaiveDate does not implement Serialize. What is the likely cause and fix?
Show answer
The chrono crate provides its serde implementations behind an optional serde feature, and that feature is not enabled. Because of the orphan rule, you cannot implement Serialize for NaiveDate yourself. Enable it with chrono = { version = "0.4", features = ["serde"] } in Cargo.toml.