Sub topic 4
Deriving the traits
This chapter assumes you know Rust structs, enums, traits, generics and lifetimes, can add dependencies with Cargo, and can use Result with ?. It also assumes you have read the earlier chapters on the serde data model and the Serialize and Deserialize traits. Here you will see what #[derive(Serialize, Deserialize)] produces, which types it accepts, how it handles generics and lifetimes, and which errors you will meet most often.
What the derive does
A derive macro is a function that runs at compile time. It reads your type definition and emits Rust code. For serde, that code is an impl Serialize for T block, an impl<'de> Deserialize<'de> for T block, or both.
The generated Serialize implementation does the same job as the manual one you would write. It calls the matching method on the Serializer, such as serialize_struct, and then serializes each field in declaration order. The generated Deserialize implementation defines a Visitor that accepts the shapes your type can be built from, and then asks the Deserializer to drive it.
Because the code is generated, you pay no runtime cost for reflection. There is none. The generated code is ordinary monomorphized Rust, which is why serde is fast.
Enabling the derive
The macros live in a separate crate, serde_derive, and serde re-exports them only when the derive feature is on. Use this in Cargo.toml:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"Every field must implement the trait
The derive only writes the glue. It does not know how to serialize your fields. For each field it calls the field type's own Serialize or Deserialize implementation. Therefore, every field type must implement the trait you derive.
Primitives, String, Vec<T>, Option<T>, HashMap<K, V>, tuples and arrays already implement both traits, as long as their contents do. For your own types, derive the traits on each one:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Address {
city: String,
zip: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct Person {
name: String,
address: Address,
tags: Vec<String>,
}
fn main() -> Result<(), serde_json::Error> {
let person = Person {
name: "Ada".to_string(),
address: Address {
city: "London".to_string(),
zip: "N1".to_string(),
},
tags: vec!["math".to_string(), "code".to_string()],
};
let json = serde_json::to_string(&person)?;
println!("{json}");
// {"name":"Ada","address":{"city":"London","zip":"N1"},"tags":["math","code"]}
let back: Person = serde_json::from_str(&json)?;
println!("{back:?}");
Ok(())
}If Address did not derive Serialize, the compiler would report an unsatisfied trait bound such as `the trait bound Address: Serialize is not satisfied. The error points at the field inside the derive expansion, so the span can look odd. The fix is to derive the trait on Address` or on whichever field type the error names.
Types from other crates are a common source of this error. chrono, uuid, url and similar crates usually offer a serde Cargo feature that adds the implementations. Enable it on that crate, for example uuid = { version = "1", features = ["serde"] }.
The shapes the derive supports
The derive works on structs and enums. Each kind of definition maps to a different part of the serde data model, so it produces a different JSON shape.
| Rust definition | Example value | JSON output |
|---|---|---|
| Named-field struct | `Named { a: 1 }` | `{"a":1}` |
| Newtype struct (one field) | `Meters(3.5)` | `3.5` |
| Tuple struct (several fields) | `Pair(1, "a")` | `[1,"a"]` |
| Unit struct | `Marker` | `null` |
| Unit enum variant | `Shape::Unit` | `"Unit"` |
| Newtype enum variant | `Shape::Circle(1.5)` | `{"Circle":1.5}` |
| Tuple enum variant | `Shape::Rect(1.0, 2.0)` | `{"Rect":[1.0,2.0]}` |
| Struct enum variant | `Shape::Named { w: 2.0 }` | `{"Named":{"w":2.0}}` |
The newtype case matters in practice. A newtype struct is transparent: Meters(3.5) serializes as the bare number, not as a one-element array. This lets you wrap primitives in distinct types for safety without changing the wire format.
This program prints every row in the table:
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Named {
a: i32,
}
#[derive(Serialize, Deserialize)]
struct Meters(f64);
#[derive(Serialize, Deserialize)]
struct Pair(i32, String);
#[derive(Serialize, Deserialize)]
struct Marker;
#[derive(Serialize, Deserialize)]
enum Shape {
Unit,
Circle(f64),
Rect(f64, f64),
Named { w: f64 },
}
fn main() -> Result<(), serde_json::Error> {
println!("{}", serde_json::to_string(&Named { a: 1 })?);
println!("{}", serde_json::to_string(&Meters(3.5))?);
println!("{}", serde_json::to_string(&Pair(1, "a".to_string()))?);
println!("{}", serde_json::to_string(&Marker)?);
println!("{}", serde_json::to_string(&Shape::Unit)?);
println!("{}", serde_json::to_string(&Shape::Circle(1.5))?);
println!("{}", serde_json::to_string(&Shape::Rect(1.0, 2.0))?);
println!("{}", serde_json::to_string(&Shape::Named { w: 2.0 })?);
Ok(())
}The enum output above uses serde's default layout, called externally tagged. A later chapter covers how to choose other layouts.
Unions cannot derive the traits. Serde rejects them at compile time.
Deriving only one direction
You do not have to derive both traits. A type that you only write out, such as a log record, needs only Serialize. A type that you only read, such as a parsed config, needs only Deserialize. Deriving only what you use keeps compile times lower and lets you put attributes that apply to one direction on the type without breaking the other.
Some attributes behave differently in each direction. Take #[serde(skip)] on a field. When serializing, the field is left out. When deserializing, the field is not read and is filled with Default::default(), so the field's type must implement Default:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Session {
id: u64,
#[serde(skip)]
cache: Vec<u8>,
}
fn main() -> Result<(), serde_json::Error> {
let session = Session { id: 7, cache: vec![1, 2, 3] };
let json = serde_json::to_string(&session)?;
println!("{json}"); // {"id":7}
let back: Session = serde_json::from_str(&json)?;
println!("{back:?}"); // Session { id: 7, cache: [] }
Ok(())
}Generics and trait bounds
For a generic type, the derive adds a bound to each type parameter automatically. In struct Page<T>, the generated Serialize impl is impl<T: Serialize> Serialize for Page<T>, and the Deserialize impl requires T: Deserialize<'de>. You do not write these bounds yourself.
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Page<T> {
items: Vec<T>,
total: usize,
}
fn load<T: DeserializeOwned>(input: &str) -> Result<T, serde_json::Error> {
serde_json::from_str(input)
}
fn main() -> Result<(), serde_json::Error> {
let page = Page { items: vec![1, 2, 3], total: 3 };
let json = serde_json::to_string(&page)?;
println!("{json}"); // {"items":[1,2,3],"total":3}
let back: Page<i32> = load(&json)?;
println!("{back:?}");
Ok(())
}The helper load shows the second common bound. Deserialize<'de> carries a lifetime 'de that ties the value to the input it was parsed from. DeserializeOwned means "deserializable from any input lifetime", which in practice means the result owns all its data and does not borrow from the input. Use it for generic functions that parse an input and return the value, because the input string is dropped when the function returns.
Lifetimes in derived types
If your struct has a lifetime parameter, the derived Deserialize impl uses that lifetime as part of its relationship with 'de. A field of type &'a str or &'a [u8] is borrowed from the input automatically. A field of type Cow<'a, str> is not. It needs #[serde(borrow)], as the borrowing chapter explains.
Such a struct implements Deserialize<'de> only for a matching input lifetime. It does not implement DeserializeOwned. If a generic function demands DeserializeOwned and you pass a borrowing type, the compiler reports that the trait bound for<'de> Deserialize<'de> is not satisfied. Either switch the field to an owned type such as String, or relax the function bound to T: Deserialize<'de>.
Common errors
- Derive macro not found. The
derivefeature is missing fromserdeinCargo.toml. - Trait bound not satisfied on a field. The field's type does not implement the trait. Derive it, or enable the
serdefeature of the crate that defines the type. Defaultnot implemented. A field marked#[serde(skip)]or#[serde(default)]needsDefault, or a function named withdefault = "path".DeserializeOwnednot satisfied. The type borrows from its input. Use an owned field type or relax the bound.- Missing
use. The derive needs the macro name in scope, so writeuse serde::{Deserialize, Serialize};. Writing#[derive(serde::Serialize)]also works without the import.
Inspecting the generated code
When a derive behaves unexpectedly, look at what it generated. The cargo-expand tool prints your crate after macro expansion. Install it with cargo install cargo-expand, then run cargo expand in your project. The output is verbose, but it shows the exact serialize_struct calls, the field names, and the visitor types. This helps when you want to learn how to write a manual implementation, which a later chapter covers.
Exercise
You define struct Temperature(f64); and derive Serialize and Deserialize. What JSON does serde_json::to_string(&Temperature(21.5)) produce, and what does your answer say about newtype structs?
Show answer
It produces 21.5, a bare number with no array or object around it. A newtype struct (a tuple struct with one field) is serialized as its inner value, so you can wrap a primitive in a distinct type without changing the JSON format.
Exercise
A helper fn parse<T: DeserializeOwned>(s: &str) -> Result<T, serde_json::Error> fails to compile when you call it with struct Name<'a> { value: &'a str }. Why, and what are two ways to fix it?
Show answer
Name<'a> borrows from the input string, so it implements Deserialize<'de> only for a matching input lifetime and not DeserializeOwned. You can change the field to an owned String, or change the helper to take a bound T: Deserialize<'de> with the input as &'de str.