简体   繁体   中英

What is the use of tag in golang struct?

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”
}

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 (ie 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"`

Example of use is json encoding/decoding in encoding/json :

type TagType struct {
    field1 bool `json:"fieldName"`
    field2 string `json:",omitempty"`
}

More details in documentation: encoding/json

You can also use XML struct tags as shown below

type SearchResult struct {
    Title  string `xml:"title,attr"`
    Author string `xml:"author,attr"`
    Year   string `xml:"hyr,attr"`
    ID     string `xml:"owi,attr"`

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM