Daaang Amy
open main menu

Go Struct Tags

/ 1 min read

Struct Tags

Struct tags are a way we can annotate our structs with meaningful context. The most common use of struct tags is to change the key names that appear on a JSON object. This is useful for when your struct field names are not appropriate for public facing responses.

These can be annotated by two backticks: ``

Example:

type Movie struct {
	ID        int64     `json:"id"`
	CreatedAt time.Time `json:"created_at"`
	Title     string    `json:"title"`
	Year      int32     `json:"year"`
	Runtime   int32     `json:"runtime"`
	Genres    []string  `json:"genres"`
	Version   int32     `json:"version"`
}

Useful JSON Struct Tag Directives

omitempty: hides a field in the JSON output if and only if the field value is empty

-: used for when you never want a particular field to appear in the JSON output

string: used to force the value to be represented as a string