How to Use Tags in Structs in Go: Syntax and Examples
In Go, you add tags to struct fields by placing a string literal after the field type inside backticks, like
FieldName type `tag:"value"`. These tags provide metadata used by packages such as encoding/json to customize behavior like JSON key names.Syntax
Struct tags are string literals placed immediately after a field's type, enclosed in backticks `. Each tag is a key-value pair in the format key:"value". Multiple tags can be separated by spaces.
- FieldName: the name of the struct field.
- type: the data type of the field.
- tag: metadata string used by other packages.
go
type Person struct { Name string `json:"name" xml:"name"` Age int `json:"age"` }
Example
This example shows how struct tags customize JSON output by changing field names and omitting empty fields.
go
package main import ( "encoding/json" "fmt" ) type Person struct { Name string `json:"name"` Age int `json:"age,omitempty"` Address string `json:"address"` } func main() { p := Person{Name: "Alice", Address: "Wonderland"} data, err := json.Marshal(p) if err != nil { fmt.Println("Error:", err) return } fmt.Println(string(data)) }
Output
{"name":"Alice","address":"Wonderland"}
Common Pitfalls
Common mistakes when using struct tags include:
- Forgetting to use backticks
`around tags, which causes syntax errors. - Using incorrect tag format, like missing quotes around values.
- Not matching tag keys expected by packages (e.g.,
jsonfor JSON encoding). - Ignoring the
omitemptyoption which controls whether empty fields are included in output.
go
type Wrong struct { Name string "json:\"name\"" // Missing backticks } type Right struct { Name string `json:"name"` // Correct tag syntax }
Quick Reference
Tips for using struct tags effectively:
- Always use backticks
`to enclose tags. - Use double quotes
"around tag values. - Separate multiple tags with spaces inside the backticks.
- Use tags to control encoding, validation, or other metadata.
- Check package documentation for supported tag keys and options.
Key Takeaways
Struct tags in Go are string literals in backticks after field types used as metadata.
Tags customize behavior like JSON key names and omitting empty fields.
Always use correct syntax: backticks around tags and quotes around values.
Common tag keys include 'json', 'xml', and others depending on the package.
Check package docs to use tags properly and avoid common mistakes.