typestar

Struct tags in Go

A tag is metadata on a field, read by reflection at run time.

type Run struct {
    Lang     string    `json:"lang"`
    TPM      float64   `json:"tpm"`
    Stars    int       `json:"stars,omitempty"`
    Note     string    `json:"-"`
    Recorded time.Time `json:"recorded_at"`
}

func encode() (string, error) {
    run := Run{Lang: "go", TPM: 104.5, Note: "private"}
    data, err := json.Marshal(run)
    if err != nil {
        return "", fmt.Errorf("marshal: %w", err)
    }
    return string(data), nil
}

How it works

  1. The convention is key:\u0022value,option\u0022 per encoder.
  2. json:\u0022-\u0022 omits a field entirely.
  3. omitempty drops the field when it holds its zero value.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
401
Tokens
83
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 47 seconds.

Type this snippet

Step 2 of 5 in Packages & build, step 22 of 26 in Standard library & project layout.

← Previous Next →