Struct tags

A struct tag is a string after a field, with a small syntax that the compiler stores and never reads. A package reads it with reflection: encoding/json for its key and options, a validator for its rules, a database mapper for its column. The layout is a space-separated list of key:"value" pairs, and every consumer has its own key.

Tag.Get and Lookup

Tag.Get("json") returns the value for the key or an empty string, and Lookup adds a boolean so a program can tell a missing key from an empty value. The struct below carries three keys, and the field with none answers empty. A tag is opaque to the compiler: a typo in a key is a decoder that silently ignores the field.

package main import ( "fmt" "reflect" ) type User struct { Name string `json:"name" validate:"required"` Age int `json:"age" validate:"min=18"` Note string `json:"-"` } func main() { t := reflect.TypeOf(User{}) name, _ := t.FieldByName("Name") fmt.Println("json:", name.Tag.Get("json")) fmt.Println("validate:", name.Tag.Get("validate")) fmt.Println("db:", name.Tag.Get("db")) value, ok := name.Tag.Lookup("validate") fmt.Println("lookup:", value, ok) note, _ := t.FieldByName("Note") fmt.Println("note json:", note.Tag.Get("json")) }

go build -o app main.go && ./app

json: name
validate: required
db:
lookup: required true
note json: -

The missing key returned an empty string and a false, and the dash is the conventional way to say "leave this field out". The tag on the field is a raw string, so a quote inside it needs escaping only when the value itself has one; the next section reads the values rather than prints them.

A validator from tags

The validate key is not in the standard library; a program that reads it gets a rule that costs one reflection pass. The function below walks the fields of a struct, reads the tag and reports a required field that is zero. It returns the field names, which a handler turns into a 400 with the list.

package main import ( "fmt" "reflect" ) type User struct { Name string `json:"name" validate:"required"` Email string `json:"email" validate:"required"` Age int `json:"age"` } func validate(v any) []string { rv := reflect.ValueOf(v) rt := rv.Type() var errs []string for i := 0; i < rt.NumField(); i++ { field := rt.Field(i) if field.Tag.Get("validate") == "required" && rv.Field(i).IsZero() { errs = append(errs, field.Name+" is required") } } return errs } func main() { u := User{Name: "ada"} errs := validate(u) fmt.Println("errors:", errs) u.Email = "ada@example.com" fmt.Println("after fill:", validate(u)) }

go build -o app main.go && ./app

errors: [Email is required]
after fill: []

The rule lives next to the field, which is what makes a tag worth its cost: a reader sees the requirement without opening a separate schema. The function only understands the exact string required; a rule such as min=18 needs a parser for the value, and a library such as go-playground/validator exists because that parser grows.

The json tag

encoding/json reads the json key for the wire name and ignores every other key. The struct below has a json tag and a db tag on the same fields; the marshalled object uses the json names, and a database mapper would read the db ones from the same struct.

package main import ( "encoding/json" "fmt" ) type Note struct { ID int `json:"id" db:"note_id"` Title string `json:"title" db:"title"` } func main() { data, err := json.Marshal(Note{ID: 1, Title: "buy milk"}) fmt.Println(string(data)) fmt.Println("error:", err) }

go build -o app main.go && ./app

{"id":1,"title":"buy milk"}
error: <nil>

The object has lower-case keys because the tags say so, and the field order follows the struct. A tag that renames a field also renames it for Unmarshal, so the client sends the same keys back. Two packages can read their own keys from one struct, which is the usual way a model serves an API and a table at once.

Options after the comma

Everything after the first comma is an option for the package that owns the key. For json the options are omitempty, string and omitzero; for another package they are whatever it defines. The program splits the value to show the key and the options, which is what a decoder does before it reads them.

package main import ( "fmt" "reflect" "strings" ) type Opt struct { Name string `json:"name,omitempty"` Age int `json:"-"` } func main() { t := reflect.TypeOf(Opt{}) name, _ := t.FieldByName("Name") tag := name.Tag.Get("json") parts := strings.Split(tag, ",") fmt.Printf("tag: %q\n", tag) fmt.Println("key:", parts[0]) fmt.Println("options:", parts[1:]) age, _ := t.FieldByName("Age") fmt.Println("age tag:", age.Tag.Get("json")) }

go build -o app main.go && ./app

tag: "name,omitempty"
key: name
options: [omitempty]
age tag: -

A tag that does not follow the syntax is still accepted by the compiler and reported by vet as struct field tag ... not compatible with reflect.StructTag.Get: bad syntax. That is why the tag of a struct that crosses a package boundary is worth a test: the failure is silent at run time and the vet check is the only warning.

The tag is a string

Three rules keep tags useful. A key is a short lower-case word, and a package documents its own keys. A value has no spaces, because a space separates one key from the next. And a tag is a compatibility promise: renaming a json key breaks every client, so the tag changes when the API version does, not when the field name does.

The next lesson follows the tags into encoding/json itself and shows the field walk, the custom marshaller and the errors that come out of them.

Exercises

  1. Add a db tag to every field and print Tag.Get("db") for each. Which field would a mapper read, and what does it do with a missing one?
  2. Change a json tag to json:",omitempty" and marshal a zero value. What does the key become, and why is the name kept?
  3. Write a tag with a space in the value and run vet. What does it report, and why does the compiler accept the struct?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a struct tag?

    Answer

    A string after a field that reflection can read

    The compiler stores it and never interprets it.

  2. What does Tag.Get return for a missing key?

    Answer

    An empty string

    Lookup adds the boolean.

  3. What does a dash in a json tag mean?

    Answer

    The field is left out

    It is the conventional skip.

  4. What separates two keys in one tag?

    Answer

    A space

    A comma separates options inside one key.

  5. How does encoding/json read a field name?

    Answer

    From the json key of the tag, or the field name

    Other keys are ignored by the package.

  6. What does omitempty do?

    Answer

    Drops the key for a zero value

    A struct needs a pointer to be omitted.

  7. Where do tag options go?

    Answer

    After the first comma in the value

    The owning package defines them.

  8. What does vet say about a malformed tag?

    Answer

    struct field tag ... not compatible with reflect.StructTag.Get

    The compiler accepts the struct.

  9. Why is a json key a compatibility promise?

    Answer

    Renaming it breaks every client that parses the old key

    The tag is the wire contract.

  10. Can two packages read one struct?

    Answer

    Yes, each reads its own tag key

    That is how a model serves an API and a table.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev