Sub topic 13
Writing a Serialize implementation by hand
This chapter assumes you know the Serialize trait from the earlier chapters, have used #[derive(Serialize)] and serde_json, and are comfortable with generics and trait bounds. Examples use these dependencies:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"When the derive is not enough
The derive covers most types. A hand-written implementation is worth the extra code in a few cases:
- You need an output field that is computed and not stored, such as an area derived from width and height.
- A type has one shape in memory but a different one on the wire, and
serialize_withon a single field cannot express the change. - You are serializing a type you do not own through a wrapper type.
- You want to see exactly what the derive generates, so you can debug a format's behavior.
If only one field needs special handling, use #[serde(serialize_with = "...")] instead. It is shorter and keeps the derive for everything else.
The shape of the trait
Serialize has one method:
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer;Your implementation never mentions JSON. It receives a Serializer, which is the format's side of the serde data model, and calls exactly one method on it that matches the shape of your value. The return type S::Ok is whatever the format produces. For serde_json::to_string that is () because the text is written to an internal buffer. S::Error is the format's error type, so you pass failures upward with ? and never create your own.
The Serializer consumes self. You can call only one top-level method on it, and that call is your whole answer.
Choosing a method
Pick the Serializer method that matches the data model shape you want to emit. The shape you choose, not the Rust type, decides how the output looks.
| You want to emit | Call | Follow-up |
|---|---|---|
| A number, bool, or char | `serialize_u32`, `serialize_f64`, `serialize_bool`, and so on | None |
| A string | `serialize_str` | None |
| A missing or present value | `serialize_none`, `serialize_some(&value)` | None |
| A struct with named fields | `serialize_struct(name, len)` | `serialize_field`, then `end` |
| A list of values | `serialize_seq(len)` | `serialize_element`, then `end` |
| Key-value pairs with dynamic keys | `serialize_map(len)` | `serialize_entry`, then `end` |
| A fixed-size group | `serialize_tuple(len)` | `serialize_element`, then `end` |
| A unit enum variant | `serialize_unit_variant(name, index, variant)` | None |
Compound shapes return a helper object such as SerializeStruct. You feed it the parts and call end() to finish.
A struct by hand
This is the basic pattern for a struct with two fields:
use serde::ser::{Serialize, SerializeStruct, Serializer};
struct Point {
x: i32,
y: i32,
}
impl Serialize for Point {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut state = serializer.serialize_struct("Point", 2)?;
state.serialize_field("x", &self.x)?;
state.serialize_field("y", &self.y)?;
state.end()
}
}
fn main() -> Result<(), serde_json::Error> {
println!("{}", serde_json::to_string(&Point { x: 3, y: 4 })?); // {"x":3,"y":4}
Ok(())
}The sequence of calls is the whole contract. The diagram shows it.
Each field value is passed as &dyn-like generic input: serialize_field accepts any &T where T: Serialize. Your i32 fields work because i32 already implements Serialize. Types nest this way without any extra code.
Adding a computed field
A hand-written implementation can emit fields that do not exist on the struct. Here area is calculated during serialization:
use serde::ser::{Serialize, SerializeStruct, Serializer};
struct Rectangle {
width: f64,
height: f64,
}
impl Serialize for Rectangle {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut state = serializer.serialize_struct("Rectangle", 3)?;
state.serialize_field("width", &self.width)?;
state.serialize_field("height", &self.height)?;
state.serialize_field("area", &(self.width * self.height))?;
state.end()
}
}
fn main() -> Result<(), serde_json::Error> {
let rect = Rectangle { width: 3.0, height: 2.5 };
println!("{}", serde_json::to_string(&rect)?); // {"width":3.0,"height":2.5,"area":7.5}
Ok(())
}The length argument is 3 because three fields are written. This type only serializes. If you also derive Deserialize for it with deny_unknown_fields, the extra area key would be rejected on the way back in, so decide whether the type needs to round-trip.
Sequences
Use serialize_seq when the output is a list. This wrapper writes each pair as a two-element array:
use serde::ser::{Serialize, SerializeSeq, Serializer};
struct Path(Vec<(i32, i32)>);
impl Serialize for Path {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
for point in &self.0 {
seq.serialize_element(point)?;
}
seq.end()
}
}
fn main() -> Result<(), serde_json::Error> {
let path = Path(vec![(0, 0), (1, 2)]);
println!("{}", serde_json::to_string(&path)?); // [[0,0],[1,2]]
Ok(())
}The argument is Option<usize> because some iterators do not know their length up front. Pass None in that case. Many formats accept None, but some need a known length. Pass Some whenever you can.
When the loop only forwards elements, Serializer offers a shortcut: serializer.collect_seq(&self.0) does the same work in one line. collect_map and collect_str exist for the same reason. collect_str takes anything that implements Display and writes it as a string.
Enum variants
A unit variant is a variant with no data. Serialize it with the variant's position and name:
use serde::{Serialize, Serializer};
enum Level {
Low,
High,
}
impl Serialize for Level {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Level::Low => serializer.serialize_unit_variant("Level", 0, "Low"),
Level::High => serializer.serialize_unit_variant("Level", 1, "High"),
}
}
}
fn main() -> Result<(), serde_json::Error> {
println!("{}", serde_json::to_string(&Level::High)?); // "High"
Ok(())
}JSON uses the variant name. A compact binary format may use the index (1) instead. Supply both, because you do not know which format the caller will pick. Variants that carry data use serialize_newtype_variant, serialize_tuple_variant, and serialize_struct_variant. These take the same name and index arguments plus the payload.
If you want a unit variant to appear as a plain number in every format, call serialize_u8 instead. That is a deliberate choice to bypass the format's own enum handling.
Gotchas
The compiler checks types but not the contract between your calls. These mistakes compile cleanly:
- Wrong length.
serde_jsonignores the length hint for structs, so a miscountedserialize_struct("Rectangle", 2)still prints correct JSON. A format that uses the hint to size a header may produce corrupt output or an error. Count the fields you actually write. - Forgetting
end(). Dropping the helper without callingend()leaves the output unfinished. In JSON you may get a missing closing brace. The#[must_use]-style warnings do not always catch this, so always finish withstate.end()as the last expression. - Early
?returns. Use?on every call. If one field fails, the error must reach the caller. - Format assumptions. Do not branch on what you think the format is. If you need
S::is_human_readable(), call it on the serializer. It returnstruefor JSON andfalsefor most binary formats, which is the supported way to emit a string in one and bytes in the other. - Skipped fields. A derive can skip a field with
skip_serializing_if. By hand, you decide with anifand then must adjust the length passed toserialize_struct. Alternatively, callstate.skip_field("name"), which tells the format the field is absent.
Exercises
Exercise
A struct has three fields, but your implementation calls serialize_struct("Config", 2) and then writes all three. With serde_json the output looks correct. Why is this still a bug?
Show answer
The length argument is part of the contract with the Serializer. serde_json ignores it for structs, so the bug is hidden. A format that uses the count to write a header or pre-allocate space may produce wrong output or return an error. The count must equal the number of fields actually serialized.
Exercise
Write the body of serialize for struct Celsius(f64); so that Celsius(21.5) becomes the JSON string "21.5C".
Show answer
Use a single primitive call: serializer.serialize_str(&format!("{}C", self.0)). The value is one string in the data model, so no helper object and no end() call are needed.