A struct tag tells a Go encoding package how a struct field corresponds to encoded data. Put the tag after the field type, inside backticks: `Name string ` followed by `json:"name"` in backticks maps the Go field `Name` to the JSON field `name`. The names need not match. section 3.1.3
Listing 3.4 bookworm.go: Bookworm and Book structures
// A Bookworm contains the list of books on a bookworm's shelf.
type Bookworm struct {
Name string `json:"name"` #1
Books []Book `json:"books"` #2
}
// Book describes a book on a bookworm's shelf.
type Book struct {
Author string `json:"author"`
Title string `json:"title"`
}
The Bookworm and Book declarations show JSON tags on exported fields, including a slice that receives a list of books. section 3.1.3
Tags do not make an inaccessible field writable. Keep fields exported so `encoding/json` or `encoding/xml` can fill them; the containing struct type itself can remain unexported. Decode into a pointer to the destination value, and handle decoding errors. section 3.1.3 section 6.5.4
Listing 6.43 envelope.go: Structures used for XML decoding
type envelope struct {
Rates []currencyRate `xml:"Cube>Cube>Cube"` #1
}
type currencyRate struct {
Currency string `xml:"currency,attr"` #2
Rate float64 `xml:"rate,attr"`
}
The XML tags select nested `Cube` elements with `Cube>Cube>Cube` and read `currency` and `rate` attributes with `,attr`. This maps the response into fields named for their purpose rather than for the XML nodes. section 6.5.4
Choose tags from the data you actually receive: a JSON file can decode into a slice of tagged structs, while an HTTP response body can feed an XML decoder. Tags define the field mapping; the decoder still needs a matching destination shape and a pointer to populate it. section 3.1.3 section 6.5.4


