Sub topic 4
Deriving the traits
This chapter assumes you know the Serialize and Deserialize traits and the serde data model from the earlier chapters. It also assumes you can add a Cargo dependency and read a Rust compiler error.
What the derive does
Writing #[derive(Serialize, Deserialize)] runs a procedural macro at compile time. The macro reads your type definition and generates impl Serialize for T and impl<'de> Deserialize<'de> for T. The generated code walks your fields and calls the matching data model methods, such as serialize_struct and serialize_field. Nothing happens at run time that you could not have written by hand.
Enabling the macros
The derive macros live behind a Cargo feature. Without it, use serde::Serialize imports only the trait and not the macro.
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"Nested types
A derive works when every field type already implements the trait. Standard types such as String, Vec<T>, Option<T> and the integers do. Your own types qualify once you derive them too.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Address {
city: String,
zip: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct Customer {
id: u32,
name: String,
tags: Vec<String>,
address: Address,
}
fn main() -> Result<(), serde_json::Error> {
let customer = Customer {
id: 7,
name: "Ada".to_string(),
tags: vec!["vip".to_string()],
address: Address {
city: "London".to_string(),
zip: "N1".to_string(),
},
};
let json = serde_json::to_string(&customer)?;
println!("{json}");
// {"id":7,"name":"Ada","tags":["vip"],"address":{"city":"London","zip":"N1"}}
let back: Customer = serde_json::from_str(&json)?;
println!("{back:?}");
Ok(())
}You can derive only one trait if you need one direction. A type you only send out needs just Serialize.
Generic types
For a generic struct, the derive adds bounds to the generated impl. Serialize requires T: Serialize, and Deserialize requires T: Deserialize<'de>.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Page<T> {
items: Vec<T>,
total: usize,
}
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> = serde_json::from_str(&json)?;
println!("{back:?}");
Ok(())
}Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `cannot find derive macro Serialize` | The `derive` feature is missing | Add `features = ["derive"]` to `serde` |
| `the trait bound Inner: Serialize is not satisfied` | A field type has no implementation | Derive the trait on `Inner`, or use a field attribute |
| `the trait Deserialize<'de> is not implemented` for a type from another crate | The foreign type does not support serde | Enable the crate's serde feature, or wrap the type |
| Type annotations needed on `from_str` | The compiler cannot infer the target type | Write `let x: T = ...` or `from_str::<T>(...)` |
Limits of the derive
The derive follows the shape of your type. Without attributes, field names become JSON keys exactly as written, and every field is required on input except Option<T> fields, which become None when missing. Later chapters cover the attributes that change this behavior.
Exercise
You derive only Serialize on a struct Report. A teammate then calls serde_json::from_str::<Report>(text). What happens, and what is the fix?
Show answer
It fails at compile time because Report does not implement Deserialize<'de>. Add Deserialize to the derive list, and make sure every field type also implements it.