liveBook · Manning

Serialization

As explained in Go in Practice, Second Edition

Serialization is the conversion of in-memory data into a representation suitable for storage or transmission.

Serialization converts in-memory data into a representation suitable for storage or transmission. In Go, a struct can be serialized to a custom key-value format and reconstructed from that representation. section 13.2.3

A reflection-based serializer follows a small implementation cycle:

  • Annotate struct fields with tags that name their serialized keys. section 13.2.3
  • Implement Marshal and Unmarshal methods with predictable byte and error parameters. section 13.2.3
  • Inspect struct fields with reflection, format values, parse input lines, and assign converted values. section 13.2.3
  • Return errors for unsupported input shapes and handle type conversion while populating fields. section 13.2.3
Listing 13.11 The Processes struct with annotations
type Processes struct {
     Total    int     `ini:"total"`
     Running  int     `ini:"running"`
     Sleeping int     `ini:"sleeping"`
     Threads  int     `ini:"threads"`
     Load     float32 `ini:"load"`
}

Tags map Go field names such as Total and Load to serialized keys such as total and load. section 13.2.3

Listing 13.12 The Marshal and Unmarshal patterns
func Marshal(v interface{}) ([]byte, error) {}
func Unmarshal(data []byte, v interface{}) error {}

The Marshal and Unmarshal signatures establish the reusable boundary between in-memory values and encoded byte data. section 13.2.3

Round-tripping process statistics

A Processes struct containing Total, Running, Sleeping, Threads, and Load is marshaled into lines such as total=23 and load=1.8. The same bytes are then unmarshaled into a new Processes value, reproducing the original fields. Running the program uses go run load.go. section 13.2.3

How Go in Practice, Second Edition covers it

How deep it goes
Implements field tagging, validation, formatting, scanning, parsing, and type conversion, while handling only structs.
Examples
Demonstrates tagged process statistics, key-value output, go run execution, and reconstruction into a second struct.
What it assumes
Assumes Go structs and interfaces, while explaining reflection, struct tags, field kinds, and runtime type inspection.
What you can do after
Build it from scratch by implementing reflection-based Marshal and Unmarshal functions for a tagged Go struct.
How it connects
Connects serialization with reflection, struct tags, marshaling, unmarshaling, and code generation.

Also explained in

Compare how 24 books explain serialization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.