Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 147 ยท Structs and Methods

Struct Tags

Learn Go struct tags - the key:"value" syntax, json and xml tags, omitempty and the dash, omitzero, reading tags with reflect, and writing your own validation tags.

A struct tag is a short string of metadata attached to a struct field. The compiler ignores it, and so does your running program, unless some code asks to read it. Libraries read tags through reflection to learn things the type system can't say, such as "this field is called user_name in JSON" or "this field is required". Tags are how encoding/json, encoding/xml, database mappers and validation libraries customize behavior per field, without you writing any conversion code.

This lesson explains the tag syntax and its easy-to-make mistakes, the json tag options you will use daily (omitempty, omitzero, -, string), how embedded structs behave, how to read tags yourself with the reflect package, and how to build a small custom validator. It follows Structs, and the examples use custom types and Methods.

Tag syntax

A tag is a string literal placed after the field's type. By convention it is a raw string (backticks) containing space-separated key:"value" pairs:

Go
type User struct {
	ID    int    `json:"id"`
	Name  string `json:"name" db:"user_name" validate:"required"`
	Email string `json:"email,omitempty"`
}

The rules matter, because mistakes fail silently:

  • The pair format is key:"value", with no space around the colon, and the value in double quotes.
  • Pairs are separated by single spaces.
  • Each library reads only its own key and ignores the rest. A field can carry json, xml, db and validate tags side by side.
  • The value's inner format belongs to the library. For json it is a name followed by comma-separated options.
  • A tag that is malformed is not a compile error. go vet reports it (the structtag check), so run it.

Writing json: "id" with a space, or json:id without quotes, produces a tag that encoding/json silently ignores. The field then keeps its Go name in the output. Always run go vet.

JSON field names

Without tags, encoding/json uses the Go field name, and it only includes exported fields (capitalized). Real JSON APIs usually use lowercase or snake_case names, which is the first job of a tag:

Go Renaming fields with json tags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Unmarshaling also matches the tag name (and, as a convenience, matches keys case-insensitively), so one tag controls both directions.

omitempty, omitzero and the dash

After the name come options, separated by commas. These are the ones you will use:

  • omitempty skips the field when its value is "empty": false, 0, a nil pointer, a nil interface, and any empty array, slice, map or string.
  • omitzero (added in Go 1.24) skips the field when it is the zero value of its type, or when its IsZero() bool method says so. This finally works for structs and time.Time, which omitempty never skipped.
  • - as the entire name means "never encode or decode this field". json:"-," is a field really named -.
  • string encodes a number or boolean as a JSON string, as in "count":"5", which some APIs expect.
Go omitempty, omitzero, dash and string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

For the first profile, nickname, age, active, tags and joined are all gone, password never appears, and visits is a string. The second profile shows everything, including a formatted timestamp.

A classic pitfall: omitempty on a number drops a legitimate 0. If Age of 0 is meaningful ("not a newborn, a missing value"), use a pointer, *int, with omitempty: nil is omitted, while a pointer to 0 is written. Compare the two:

Go omitempty and legitimate zero values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first line is {"retries_ptr":0}: the plain int zero was swallowed, the pointer to zero survived. The second prints {}.

Embedded structs and tags

When a struct embeds another struct without a name or a tag, encoding/json flattens its fields into the parent object, matching the promotion rules from Struct Embedding. Giving the embedded field a tag turns it into a nested object instead:

Go Embedded structs flatten unless tagged

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Other encodings: XML and friends

The same idea powers encoding/xml, with extra options such as attr (write the field as an attribute) and chardata (the element's text). The tag xml:"book>title" even nests elements:

Go XML tags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Database layers (db:"user_name"), form binders (form:"email"), config loaders (yaml:"port", env:"PORT") and validators all use tags the same way. They are third-party packages, but the mechanism is exactly what you see next.

Reading tags with reflect

The reflect package gives you the raw tag string with Field.Tag. Tag.Get(key) returns the value for a key (or ""), and Tag.Lookup(key) also tells you whether the key was present, which separates a missing tag from an empty one:

Go Reading tags with reflect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

reflect.TypeFor[T]() (Go 1.22) is the modern way to get a type without creating a value. The printed lines show that Plain has an empty tag, that Notes has the value "-" for the json key, and that Get("db") returns "" where there is no db key.

Writing your own tag-driven code

Because reading tags is just reflection, you can write a tiny validator. This one understands validate:"required" and validate:"min=3" on strings and validate:"min=18" on ints:

Go A small validator driven by tags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The validator works on any struct, because it discovers fields and rules at run time. That is the power and the price of tags: flexibility, but errors in a tag only show up when the code runs (or in go vet), and reflection is slower than direct code. For hot paths, hand-written validation or generated code is faster.

Good practice

  • Run go vet to catch malformed tags and duplicate JSON names.
  • Tag exported fields only. Unexported fields are invisible to reflection-based encoders.
  • Keep tags short. Business rules belong in code; tags describe mapping and simple constraints.
  • Don't reuse API structs as database or domain models just because tags make it easy. Separate types keep one change from rippling through all layers.
  • Prefer omitzero for structs and times, omitempty for strings, slices and maps, and pointers when zero is meaningful.
  • Know the cost. Reflection on tags is done once per type by encoding/json and cached, so the tag lookup is not a runtime hot spot there.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when a field has the tag json: "id" (a space after the colon)?

    Tags are not checked by the compiler. A malformed tag is simply not recognized, so the Go field name is used. go vet finds the mistake.
  2. 2. Two fields are both tagged with omitempty: A int and B *int. A is 0 and B points to a 0. Which one is written to the JSON output?

    omitempty drops the plain zero int, but a non-nil pointer is not empty, even when it points to 0.
  3. 3. What does the tag json:"-" do?

    A tag consisting only of a dash hides the field from encoding/json completely.
  4. 4. How does encoding/json handle an untagged embedded struct?

    Embedded fields are promoted, so they appear alongside the parent fields. A tag on the embedded field makes it a nested object instead.
  5. 5. Which call tells you whether a tag key exists, even if its value is empty?

    Lookup returns the value and a boolean ok. Get returns only the string, so a missing key and an empty value look the same.

Summary

  • A tag is a raw string after a field's type, holding space-separated key:"value" pairs; the compiler never checks it.
  • json tags rename fields and add options: omitempty, omitzero (Go 1.24), - and string.
  • Only exported fields are encoded; use pointers when zero is a legitimate value.
  • Untagged embedded structs are flattened by encoding/json; a tag makes them nested.
  • encoding/xml and many third-party libraries read their own keys the same way.
  • Read tags with reflect: Tag.Get for the value, Tag.Lookup to detect presence.
  • Run go vet to catch malformed tags.

Next: Struct Memory Layout and Alignment