Field tags

A struct can also host a specific set of JSON data; all of the exported keys will have names identical to the respective fields. In order to customize the keys, Go enables us to follow field declarations in a struct with a string that should contain metadata about the field.

These tags take the form of colon separated keys/values. The value is a quoted string, which can contain additional information added using commas (such as job,omitempty). If there is more than one tag, spaces are used to separate them. Let's see a practical example that uses struct tags:

type Character struct {
Name string `json:"name" tag:"foo"`
Surname string `json:"surname"`
Job string `json:"job,omitempty"`
YearOfBirth int `json:"year_of_birth,omitempty"`
}

This example shows how two different tags can be used for the same field (we have both json and foo), and it shows how to specify a particular JSON key and introduce the omitempty tag that is used for output purposes to avoid marshaling the field if it has a zero value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.135.80