Struct tags

suggest change

Struct fields can have tags associated with them. These tags can be read by the reflect package to get custom information specified about a field by the developer.

type Account struct {
    Username      string `json:"username"`
    DisplayName   string `json:"display_name"`
    FavoriteColor string `json:"favorite_color,omitempty"`
}

In the above example, the tags are used to change the key names used by the encoding/json package when marshaling or unmarshaling JSON.

While the tag can be any string value, it’s considered best practice to use space separated key:"value" pairs:

type StructName struct {
    FieldName int `package1:"customdata,moredata" package2:"info"`
}

The encoding/json and encoding/xml packages read these tags. Separate pairs with a space. A comma belongs inside one value, as in json:"name,omitempty".

Read about using reflection to read struct tags at runtime.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents