liveBook · Manning

Attribute

As explained in Go in Practice, Second Edition

An annotation is metadata associated with program declarations or data structures to provide additional information for tools or runtime processing.

A Go struct tag attaches metadata to a field declaration. Encoders can use that metadata to control how the field appears in serialized data. section 3.1.5

Listing 3.4 Formatting data as JSON
package main

import (
    "fmt"
    "encoding/json"
)

type Animal struct {                       #1
    Name string `json:"animal_name"`                   #2
    ScientificName string `json:"scientific_name"`     #2
    Weight float32 `json:"animal_average_weight"`      #2
}

func main() {
    a := Animal{
        Name: "cat",
        ScientificName: "Felis catus",
        Weight: 10.5,
    }                     #3

    output, err := json.Marshal(a)
    if err != nil {
        panic("couldn't encode json")
    }
    fmt.Println(string(output))     #4
}

The Animal fields use json tags to choose JSON property names; encoding/json marshals the struct using those names. The fields must be exported for the encoder to access them. section 3.1.5

How Go in Practice, Second Edition covers it

How deep it goes
Demonstrates tag syntax, exported-field requirements, and JSON output, but not format-specific encoding internals.
Examples
Shows an Animal struct with tags that rename its fields in marshaled JSON.
What you can do after
Apply struct tags with encoding/json to choose JSON property names for exported struct fields.
How it connects
Connects struct tags to Go structs, exported fields, JSON encoding, and XML encoding.

Also explained in

Compare how 26 books explain attribute →

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.