← Back to Go Course | Chapter 6: Structs & Methods | Lesson 6 of 6

Struct Tags

A struct tag is a little note attached to a field, like a sticky label that tells other tools (such as the JSON encoder) exactly what to call that field when saving or sending it.

Writing a Struct Tag

A struct tag is a raw string (written between backticks) placed after a field's type, conventionally holding space-separated key:"value" pairs that libraries like encoding/json read via reflection.

Example: Writing a Struct Tag

markup
package main

import "fmt"

type Product struct {
	Name  string `json:"name"`
	Price float64 `json:"price"`
}

func main() {
	p := Product{Name: "Notebook", Price: 3.5}
	fmt.Printf("%+v\n", p)
}

Using Tags with encoding/json

The json tag controls exactly what key name is used when a struct is converted to JSON, letting you follow Go's exported-field naming convention (Name) while producing lowercase JSON keys ("name") that match common API conventions.

Note: Only capitalized (exported) fields are ever visible to encoding/json.

Example: Using Tags with encoding/json

markup
package main

import (
	"encoding/json"
	"fmt"
)

type Product struct {
	Name  string  `json:"name"`
	Price float64 `json:"price"`
}

func main() {
	p := Product{Name: "Notebook", Price: 3.5}
	data, _ := json.Marshal(p)
	fmt.Println(string(data))
}

Omitting Empty Fields

Adding ',omitempty' to a json tag tells the encoder to skip that field entirely in the output when it holds its zero value, which keeps generated JSON compact when many fields are optional.

Example: Omitting Empty Fields

markup
package main

import (
	"encoding/json"
	"fmt"
)

type Product struct {
	Name string `json:"name"`
	Note string `json:"note,omitempty"`
}

func main() {
	p := Product{Name: "Pen"}
	data, _ := json.Marshal(p)
	fmt.Println(string(data))
}
Common Mistakes
  1. Getting the backtick-quoted tag string syntax wrong (mismatched quotes inside), which silently causes the tag to be ignored rather than erroring.
  2. Forgetting a struct field must be exported (capitalized) for encoding/json to see it at all, regardless of its tag.
  3. Misspelling a tag key like json as JSON, which reflection-based libraries won't recognize.
Chapter Summary
  • A struct tag is a string literal attached to a field, written in backticks after its type.
  • encoding/json reads json:"name" tags to control the field name and behavior during marshaling.
  • Only exported (capitalized) fields are visible to encoding/json regardless of tags.
  • Tags are read at runtime via reflection -- they have no effect on how the Go compiler treats the field.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.