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























