Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of tag in golang struct?

Tags:

go

I don't understand the significance of struct tags. I have been looking them, and noticed that they can be used with reflect package. But I don't know any practical uses of them.

type TagType struct { // tags
    field1 bool   “An important answer”
    field2 string “The name of the thing”
    field3 int    “How much there are”
}
like image 877
user Avatar asked Dec 20 '22 16:12

user


1 Answers

The use of tags strongly depends on how your struct is used.

A typical use is to add specifications or constraints for persistence or serialisation.

For example, when using the JSON parser/encoder, tags are used to specify how the struct will be read from JSON or written in JSON, when the default encoding scheme (i.e. the name of the field) isn't to be used.

Here are a few examples from the json package documentation :

// Field is ignored by this package.
Field int `json:"-"`

// Field appears in JSON as key "myName".
Field int `json:"myName"`

// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`

// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`
like image 150
Denys Séguret Avatar answered Jan 09 '23 10:01

Denys Séguret