Sub topic 1
What serde does and how it is organized
Prerequisites
This chapter assumes Rust basics, including structs, traits, generics, lifetimes, Result, the ? operator, Cargo, and JSON.
What serde does and how it is organized
Serde is a Rust framework for converting typed Rust values into data formats and converting formatted data back into Rust values.
The first direction is serialization: turning a Rust value into JSON, TOML, YAML, or another format. The reverse is deserialization: reading formatted data and creating a Rust value.
Serde itself does not implement every format. It defines common traits and a data model. Separate crates, such as serde_json and toml, connect those traits to particular formats.
The serde data model as a common middle layer
The Serde data model is a shared description of values. It includes booleans, integers, strings, sequences, maps, options, and structs.
A Rust struct does not need to know how JSON represents a map. JSON does not need to know the details of every Rust struct. Instead, both sides communicate through the data model:
- A serializer asks a Rust value to describe itself using the model.
- A format serializer writes that description as JSON or another format.
- A format deserializer reads input and presents model values to a Rust type.
This separation lets one Rust type work with several formats.
The `Serialize` and `Deserialize` traits
Serialize describes how a value produces data. Deserialize describes how a type can be constructed from data. Format crates provide the concrete serializer and deserializer implementations.
These traits are generic over the format, so application code can use the same type with different formats.
Deriving the traits
Serde's derive macros generate trait implementations from a struct or enum definition.
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct User {
id: u32,
name: String,
}
fn main() -> Result<(), serde_json::Error> {
let user = User {
id: 1,
name: "Ada".to_string(),
};
let json = serde_json::to_string(&user)?;
let restored: User = serde_json::from_str(&json)?;
println!("{json}");
println!("{restored:?}");
Ok(())
}The derive macro is usually the best starting point. Later, attributes or manual implementations handle formats that do not match Rust's default representation.
Exercise
Which crate provides JSON conversion while serde provides the common traits?
Show answer
serde_json provides JSON conversion; serde provides traits such as Serialize and Deserialize.