Sub topic 3
The Serialize and Deserialize traits
This chapter assumes you know Rust traits, generics, and lifetimes, and that you can add a dependency with Cargo. It also assumes you have read the previous chapter on the serde data model.
Two traits, two directions
serde puts the work of converting data into two traits in the serde crate:
Serializeis implemented by a type that can describe itself to a format.Deserializeis implemented by a type that can build itself from a format.
A format crate such as serde_json implements the other side of each conversation. It provides a Serializer and a Deserializer.
| Item | Implemented by | Role |
|---|---|---|
| `Serialize` | Your data types | Describes a value in terms of the data model |
| `Serializer` | Format crates | Turns data model calls into output such as JSON text |
| `Deserialize<'de>` | Your data types | Builds a value from data model events |
| `Deserializer<'de>` | Format crates | Reads input and drives the construction |
No type knows about any format, and no format knows about any type. They only meet at the data model.
The trait signatures
Both traits have a single method. Here are the definitions, simplified slightly:
pub trait Serialize {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer;
}
pub trait Deserialize<'de>: Sized {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>;
}Three details matter:
serializeis generic overS. The compiler generates a separate copy for each format, so there is no dynamic dispatch.S::OkandS::Errorbelong to the format. A JSON serializer has a different error type than a TOML one.Deserializetakes noself. It is a constructor, so it needsSized. The'delifetime is the lifetime of the input, which makes borrowing from it possible. A later chapter covers that.
Using the traits as bounds
Standard library types already implement both traits, including integers, String, Vec<T>, Option<T>, HashMap, and tuples. You can therefore write generic code against the traits:
use serde::{de::DeserializeOwned, Serialize};
fn round_trip<T>(value: &T) -> Result<T, serde_json::Error>
where
T: Serialize + DeserializeOwned,
{
let json = serde_json::to_string(value)?;
println!("{json}");
serde_json::from_str(&json)
}
fn main() -> Result<(), serde_json::Error> {
let numbers = round_trip(&vec![1u8, 2, 3])?; // [1,2,3]
let pair = round_trip(&("Ada".to_string(), Some(36u32)))?; // ["Ada",36]
println!("{numbers:?} {pair:?}");
Ok(())
}Use these dependencies:
[dependencies]
serde = "1"
serde_json = "1"The derive feature is not needed here, because only standard types are involved.
DeserializeOwned is shorthand for for<'de> Deserialize<'de>. It means the result owns all its data and does not borrow from the input string. That is required here because json is dropped when the function returns.
Where implementations come from
You get an implementation in one of two ways:
- Derive it with
#[derive(Serialize, Deserialize)]. This is the normal route, and the next chapter covers it. - Write it by hand, which a later chapter covers. This is useful when the derive cannot express the shape you need.
Both routes produce the same kind of trait implementation. Callers such as serde_json::to_string cannot tell them apart.
Common errors
- "the trait bound
X: Serializeis not satisfied":Xlacks an implementation. Derive it, or implement it by hand. CheckSerializeon third-party types too, since many crates hide it behind a feature flag. - Format-specific failures: Both traits are format-neutral, so a type can implement them and still fail at runtime. For example, JSON object keys must be strings, so a
HashMap<(i32, i32), _>fails to serialize to JSON.
Exercise
In round_trip above, why is the bound DeserializeOwned rather than Deserialize<'de>, and what would break for a type with a &str field?
Show answer
The input String is local to the function and is dropped on return, so the returned T cannot borrow from it. DeserializeOwned requires T to deserialize from input of any lifetime without borrowing. A type with a &str field only implements Deserialize<'de> tied to the input's lifetime, so it fails the DeserializeOwned bound and the call does not compile.