The Analogy: The Luggage Label
A suitcase going through an airport carries one paper label tied to the handle, and several different people read different parts of it. The airline reads the three-letter destination code. Customs reads the declared contents. The baggage system reads the barcode. Security reads the screening stamp. The suitcase itself never reads any of it, and if a handler encounters a field they do not care about, they ignore it and read their own.
A struct tag is that label. It is a string literal written after a field declaration, and the Go compiler does absolutely nothing with it -- it does not parse it, validate it, or attach meaning to it. It simply records the string in the type, where reflect.StructField.Tag can retrieve it. Everything else is convention.
The convention, documented on reflect.StructTag, is that the string holds space-separated key:"value" pairs, and that each library reads only its own key. encoding/json reads json, a SQL mapper reads db, a validator reads validate. One field, one label, several independent readers -- which is why a single User type can describe its wire format, its column names and its constraints in one place instead of three.
Where the analogy stops: because the compiler does not parse the label, a typo is invisible. Write json: "name" with a space after the colon and Tag.Get("json") returns the empty string with no complaint from anything -- your field quietly serialises under its Go name instead. Tags also participate in type identity: two struct types with identical fields but different tags are genuinely different types, though a conversion between them is allowed and ignores the tags entirely. The one real safety net is go vet, whose structtag check catches malformed syntax and duplicate names, and which runs automatically as part of go test.
Syntax or Core Structure
package main
import (
"encoding/json"
"fmt"
"reflect"
)
type User struct {
ID int `json:"id" db:"user_id" validate:"required"`
Name string `json:"name" db:"full_name" validate:"min=2"`
Email string `json:"email,omitempty" db:"email"`
Password string `json:"-" db:"pw_hash"`
Age int `json:"age,string" db:"age"`
internal string
}
func main() {
t := reflect.TypeOf(User{})
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
// Lookup distinguishes "absent" from "present but empty"; Get cannot.
j, ok := f.Tag.Lookup("json")
fmt.Printf("%-9s json=%-14q found=%-5t db=%q\n", f.Name, j, ok, f.Tag.Get("db"))
}
u := User{ID: 7, Name: "ada", Password: "s3cret", Age: 36, internal: "x"}
b, _ := json.Marshal(u)
fmt.Println(string(b))
var back User
_ = json.Unmarshal([]byte(`{"id":9,"name":"grace","age":"45","password":"nope"}`), &back)
fmt.Printf("%+v\n", back)
}
Output:
ID json="id" found=true db="user_id"
Name json="name" found=true db="full_name"
Email json="email,omitempty" found=true db="email"
Password json="-" found=true db="pw_hash"
Age json="age,string" found=true db="age"
internal json="" found=false db=""
{"id":7,"name":"ada","age":"36"}
{ID:9 Name:grace Email: Password: Age:45 internal:}
Every interesting behaviour of encoding/json is visible in those last two lines. Email vanished from the output because omitempty dropped an empty string. Password vanished because json:"-" means "never", which is also why the incoming "password":"nope" had nowhere to land and was silently discarded. Age came out as "36" -- a JSON string holding a number -- because of the ,string option, and went back in from "45" the same way. And internal was skipped on both journeys for a reason no tag can override: it is unexported.
Technical Depth: A String The Compiler Ignores
The grammar is a convention, not a rule
A field tag is any string literal at all -- a tag reading heavier than a duck compiles perfectly and means nothing to anyone. What makes tags useful is that reflect.StructTag documents a shared format and provides two methods that parse it:
| Call | Absent key | Present but empty | Notes |
|---|---|---|---|
Tag.Get("json") | "" | "" | convenient, but cannot tell the two apart |
Tag.Lookup("json") | "", false | "", true | use this whenever absent and empty differ |
string(f.Tag) | the whole raw label | what you inspect when a tag mysteriously does nothing |
The format demands key:"value" with no space around the colon, pairs separated by single spaces, and the value written as a quoted Go string. Lookup scans left to right and stops at the first key match, so a duplicate key later in the string is unreachable.
Always use a raw string literal
type A struct {
N int `json:"n"` // raw string: readable
}
type B struct {
N int "json:\"n\"" // legal, identical result, unreadable
}
Both produce the same tag string, because the tag is a string. Backticks simply spare you from escaping the quotes that the convention requires.
Tags belong to the type
Two struct types differing only in their tags are distinct types, so an A will not satisfy a parameter of type B. Since Go 1.8, however, a conversion between them is legal and ignores tags:
type Wire struct{ N int `json:"n"` }
type Store struct{ N int `db:"n"` }
w := Wire{N: 4}
s := Store(w) // fine: identical fields, tags ignored in conversions
var x any = w
_, ok := x.(Store) // false: a type assertion is not a conversion
That is the idiomatic way to keep one struct for the wire format and another for the database without copying fields by hand.
The json option grammar
| Tag | Effect |
|---|---|
json:"name" | rename the key |
json:"-" | never encode or decode this field |
json:"-," | the key is literally - (the trailing comma is the escape hatch) |
json:",omitempty" | omit false, 0, nil pointer, empty string, and empty slice/map/array |
json:",omitzero" | Go 1.24: omit the zero value, including zero structs |
json:",string" | encode a number or bool as a JSON string |
json:"name,omitempty,string" | name first, then options in any order |
The trap in that table is that omitempty does not consider an empty struct or a zero time.Time to be empty -- it has no notion of a zero struct at all, which is precisely the gap omitzero closes.
Decoding is more forgiving than encoding
json.Unmarshal matches an incoming key against the tag name first, and falls back to a case-insensitive comparison against the tag name and then the field name. So {"NAME":"x"} and {"name":"x"} both fill a field tagged json:"name". Unknown keys are ignored unless you opt in with Decoder.DisallowUnknownFields.
Embedding
An embedded struct with no json tag is flattened -- its fields appear as siblings of the outer struct's own fields. Give the embedded field a tag and it becomes a nested object instead:
type Meta struct {
Rev int `json:"rev"`
}
type Flat struct {
Meta
ID int `json:"id"`
}
type Nested struct {
Meta `json:"meta"`
ID int `json:"id"`
}
A Flat{Meta{1}, 2} encodes as {"rev":1,"id":2}; a Nested{Meta{1}, 2} encodes as {"meta":{"rev":1},"id":2}.
go vet is the only checker you get
The structtag analyser catches malformed syntax, a space after the colon, and two fields competing for the same json or xml name. It runs automatically during go test, so a tag typo in a tested package is usually caught -- but it knows nothing about your keys. A misspelt validte:"required" passes vet and does nothing forever.
Who else reads tags
| Key | Consumer |
|---|---|
json, xml | the standard library |
yaml, toml, mapstructure | third-party config decoders |
db, gorm, bun | SQL mappers |
validate, binding | validators and web frameworks |
env, flag | environment and command-line binders |
Nothing stops you from adding your own key, which is exactly what the next section does.
Real World Example: A Tag-Driven Validator
Every web form needs the same checks, and writing them by hand means an if block per field that drifts out of step with the struct. Putting the rules in a validate tag keeps each constraint next to the field it describes, and one reflective loop applies all of them.
package main
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
)
type Signup struct {
Email string `validate:"required,email"`
Name string `validate:"required,min=2,max=20"`
Age int `validate:"min=13,max=120"`
Ref string `validate:"-"`
Score float64 `validate:"min=0,max=1"`
internal string `validate:"required"`
}
var (
ErrRequired = errors.New("must not be empty")
ErrTooSmall = errors.New("too small")
ErrTooLarge = errors.New("too large")
ErrFormat = errors.New("wrong format")
ErrRule = errors.New("unusable rule")
)
// Validate reports every broken rule at once, joined into a single error.
func Validate(v any) error {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Pointer {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
return fmt.Errorf("validate: want a struct, got %s", rv.Kind())
}
rt := rv.Type()
var problems []error
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
rule, tagged := f.Tag.Lookup("validate")
if !tagged || rule == "-" || !f.IsExported() {
continue
}
for _, part := range strings.Split(rule, ",") {
name, arg, _ := strings.Cut(part, "=")
if err := check(name, arg, rv.Field(i)); err != nil {
problems = append(problems, fmt.Errorf("%s: %w", f.Name, err))
}
}
}
return errors.Join(problems...)
}
func check(rule, arg string, v reflect.Value) error {
switch rule {
case "required":
if v.IsZero() {
return ErrRequired
}
case "email":
s := v.String()
if s == "" {
return nil // "required" already reported this field
}
at := strings.IndexByte(s, '@')
if at < 1 || !strings.Contains(s[at:], ".") {
return fmt.Errorf("%w: %q is not an address", ErrFormat, s)
}
case "min", "max":
want, err := strconv.ParseFloat(arg, 64)
if err != nil {
return fmt.Errorf("%w: %s=%q", ErrRule, rule, arg)
}
got, unit := measure(v)
if rule == "min" && got < want {
return fmt.Errorf("%w: %s %g, need at least %g", ErrTooSmall, unit, got, want)
}
if rule == "max" && got > want {
return fmt.Errorf("%w: %s %g, allowed at most %g", ErrTooLarge, unit, got, want)
}
default:
return fmt.Errorf("%w: %q", ErrRule, rule)
}
return nil
}
// measure reduces a value to one number plus the noun that describes it.
func measure(v reflect.Value) (float64, string) {
switch v.Kind() {
case reflect.String:
return float64(len(v.String())), "length"
case reflect.Slice, reflect.Map, reflect.Array:
return float64(v.Len()), "length"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return float64(v.Int()), "value"
case reflect.Float32, reflect.Float64:
return v.Float(), "value"
}
return 0, "value"
}
func main() {
cases := []Signup{
{Email: "ada@lovelace.org", Name: "Ada", Age: 36, Score: 0.9},
{Email: "nope", Name: "A", Age: 9, Score: 1.5},
{Name: "Grace Hopper", Age: 45, Score: 0.5},
}
for i, c := range cases {
err := Validate(c)
if err == nil {
fmt.Printf("case %d: ok\n", i)
continue
}
fmt.Printf("case %d:\n", i)
joined, ok := err.(interface{ Unwrap() []error })
if !ok {
fmt.Println(" -", err)
continue
}
for _, e := range joined.Unwrap() {
fmt.Println(" -", e)
}
}
fmt.Println("case 1 has a too-small field:", errors.Is(Validate(cases[1]), ErrTooSmall))
fmt.Println("not a struct:", Validate(42))
}
Output:
case 0: ok
case 1:
- Email: wrong format: "nope" is not an address
- Name: too small: length 1, need at least 2
- Age: too small: value 9, need at least 13
- Score: too large: value 1.5, allowed at most 1
case 2:
- Email: must not be empty
case 1 has a too-small field: true
not a struct: validate: want a struct, got int
The tag is the data and the loop is its interpreter, which is the whole appeal of the pattern: tightening a constraint is a one-line edit to the type declaration, and the rule sits on the line that declares the thing it constrains. Two guards keep the loop honest -- rule == "-" skips Ref the way json:"-" skips a field, and f.IsExported() skips internal even though it carries validate:"required", because reflection cannot read an unexported field's value and a tag cannot grant that permission.
Notice the cooperation between required and email on case 2. An empty Email breaks both rules, but check returns nil for an empty string under email, so the user sees one message rather than two complaints about the same blank box. That kind of judgement is invisible in the tag and lives entirely in the interpreter -- the tag says what, the loop decides how it reads.
Because every problem is wrapped with %w and collected by errors.Join, the result is structured rather than a string blob. A form handler walks Unwrap() []error to render one message per field; a metrics counter asks errors.Is(err, ErrTooSmall) and gets true without parsing anything. The join also explains the field ordering: problems accumulate in declaration order, so the report is deterministic.
The fragility is worth naming out loud. validate:"min=two" compiles, passes go vet, and only fails when that field is validated -- which is why check returns ErrRule instead of panicking, and why an unknown rule name is reported rather than ignored. Writing validate:"min = 2" with spaces silently produces the rules "min " and " 2", both unknown. The defence is a test that runs Validate over a zero value of every tagged type in the package; it exercises every tag string and turns a typo into a failing test instead of a production surprise. In a hot path, cache the parsed rules in a map[reflect.Type][]rule guarded by sync.Map, because splitting strings on every request is pure waste.
Common Mistakes
- Putting a space after the colon.
json: "name"breaks the convention, soTag.Get("json")returns""and the field encodes under its Go name. Nothing warns you exceptgo vet. - Tagging an unexported field and expecting results.
encoding/jsonand every reflective library skip unexported fields unconditionally. The tag is stored, read, and then ignored because the value is unreadable. - Expecting
omitemptyto drop an empty struct. It omits false, 0, nil,""and empty slices/maps -- not a zero struct and not a zerotime.Time. Useomitzero(Go 1.24) or a pointer field. - Confusing
json:"-"with a field named-.json:"-"removes the field from JSON entirely;json:"-,"is how you actually name the key-. - Assuming decoding is case-sensitive.
{"NAME":"x"}fills a field taggedjson:"name", becauseUnmarshalfalls back to a case-insensitive match. Never rely on case to distinguish two keys. - Letting two fields claim the same JSON name.
encoding/jsonresolves the conflict by dropping both fields.go vet'sstructtagcheck is what catches this. - Believing the compiler validates tags. It records the string and moves on.
validte:"required"is a perfectly valid tag that no library will ever read. - Using
Getwhen absence matters.Getcannot distinguishdb:""from nodbkey at all. Reach forLookupwhenever the empty value is meaningful. - Forgetting that tags are part of type identity. Two structs differing only in tags are different types, so they cannot be assigned to each other -- though an explicit conversion is legal and ignores the tags.
- Marshalling a struct that holds a secret. A password, token or internal note without
json:"-"ends up in every API response and every log line that prints the payload. - Re-parsing tags on every call.
reflect.Typewalks andstrings.Spliton a hot path add up fast. Build the rule set once per type and cache it.
Best Practices
- Always write tags as raw string literals with backticks; the escaped-quote form is legal but unreadable.
- Order options as
json:"name,omitempty"-- name first, then options, comma separated with no spaces. - Run
go vet(or justgo test, which includes it) before trusting any new tag. - Prefer
LookupoverGetwhen writing your own tag consumer, and treat an absent key as "no opinion" rather than as an empty rule. - Tag every sensitive field
json:"-"the moment you add it, rather than auditing for leaks later. - Keep separate wire and storage structs when their shapes diverge, and convert between them -- conversions ignore tags, so the compiler does the copying.
- Cache anything you parse out of a tag, keyed by
reflect.Type, since a type's tags cannot change at runtime. - Write a test that feeds a zero value of each tagged type through your consumer, so typos in tag strings fail the build instead of failing silently.
Practice Exercises
- Define a
Productstruct withjsonanddbtags on every field, one field renamed, one omitted withjson:"-", and one usingomitempty. Marshal a partially filled value and explain each key that appears and each that does not. - Write
Columns(v any) []stringthat returns thedbtag of every exported field in declaration order, falling back to the lowercased field name when thedbkey is absent. UseLookup, notGet, and explain why. - Deliberately break a tag three ways -- a space after the colon, a misspelt key, and two fields sharing one
jsonname -- then rungo vetand record which of the three it catches and which it does not. - Extend the validator with a
oneof=a|b|crule and a per-type cache, then add a test that validates a zero value ofSignupto prove every tag string in the file parses.