liveBook · Manning

Struct tag

A struct tag is metadata attached to a Go struct field that guides reflection-based processing such as serialization and field mapping.

How 3 Manning books explain it

Learn Go with Pocket-Sized Projects

A struct tag is metadata attached to a Go struct field that directs packages such as encoding/xml or encoding/json how the field maps to encoded data.

How it is used
Maps JSON file fields and XML response elements or attributes into Go structs for decoding.
How deep it goes
Explains tag syntax, exported fields, pointer destinations, XML paths and attributes; defers detailed pointer explanation.
Examples
Uses a bookworm JSON file and an exchange-rate XML response with nested elements and attributes.
What you can do after
Apply it via encoding/json and encoding/xml to decode tagged structs from a file or HTTP response.

Read how Learn Go with Pocket-Sized Projects explains struct tag →

Go in Practice, Second Edition

A struct tag is a Go field annotation containing metadata, commonly expressed as whitespace-separated key-value pairs for controlling data encoding or other processing.

How it is used
Controls encoded field names and supplies metadata for custom processing such as validation and name-value file mapping.
How deep it goes
Moves from tag syntax and JSON output to runtime tag lookup and a reflection-based encoder and decoder.
Examples
Uses JSON-encoded animal data, help and validation tags, and an INI-style process-data encoder and decoder.
What you can do after
Build it from scratch: define a custom field-tag convention and read it with `reflect` in marshaling and unmarshaling code.

Read how Go in Practice, Second Edition explains struct tag →

Go in Action, Second Edition

A struct tag is metadata attached to a Go struct field that can guide reflection-based processing such as serialization and field mapping.

How it is used
Maps configuration fields between Go structs and JSON or XML representations in a validation and conversion CLI.
How deep it goes
Defines tag metadata and works through JSON and XML mappings, including options and XML-specific forms; leaves specialized validation to custom methods.
Examples
Uses a server configuration with JSON keys, omitted fields, XML attributes and elements, and conversion between formats.
What you can do after
Apply it via encoding/json and encoding/xml to map one exported-field struct to both formats in a configuration converter.

Read how Go in Action, Second Edition explains struct tag →

Related concepts

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.