Tags in Golang

Source: Internet
Author: User
Tags key string

type People struct {    Name string `json:"name"`    Age  int8   `json:"age"`}

In the course of learning, see similar to the above code, a sudden Meng a force ... Probably a look, this is Golang in the Tags syntax, the official explanation is this:

A Field declaration May is followed by an optional string literal tag, which becomes an attribute for all the fields In the corresponding field declaration. The tags is made visible through a reflection interface but is otherwise ignored.

The official explanation is not enough ground gas, beginners like me to see the equivalent is not to see, we add the actual scene in to understand this can do it.
Since the markup for a field in Golang can be obtained at reflection time, it is often used to provide information about the conversion rules during the conversion of a struct encoding, such as the JSON transformation mentioned in the following example. Of course you can also use it to store any other meta-information you want (meta-information).

Example Child

For an example of an API, get user ID 1 User information: GET /v1/user/1 . It is a simple practice to return a record in the database user table after it is retrieved in JSON format.

type User struct {    Id int  Name string  Age int8}

If you do not do any processing, the data returned at this time should be as follows:

{"Id":1,"Name":"X.FLY","Age":24}

Why are you giving me back the Hump-type property name? This is the name of the attribute when you declare the User struct.
Then change the struct property name to lowercase. No, because these attributes are all turned into private properties, do not forget that golang inside can not public/private/protected these keywords, all by the first letter case to distinguish it!
What then? With Tag .

We add tags to the struct properties:

type User struct {    Id   int    `json:"id"`    Name string `json:"name"`    Age  int8}

Deliberately do not tag the age to see the difference, the JSON format output is as follows:

{"id":1,"name":"X.FLY","Age":24}

This is the magic of Tag , will not be contaminated to the main body, and do not need to output JSON data at the time of manual processing (OK, remove the public and other key words will pay the price).

How to use

Tag can be any string, the following is a common form, do not think of a fork

In general,Tag is in the key:"value" form of this key-value pair, and if there are multiple key-value pairs, they are separated by a space.

type User struct {    Name string `json:"name" xml:"name"`}

key generally refers to the name of the package to be used, such as the JSON here indicates that the name field will be used and processed by the Encoding/json package.

If more than one value message is to be passed in, it is usually delimited with commas , .

type User struct {    Name string `json:"name,omitempty" xml:"name"`}

Omitempty indicates that the value of this field is null when decoded (Defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice , map, or string) then this field is ignored. There is also a common --which means ignoring this field directly.

Understanding Tag

In front of the tag can be obtained by the reflect package, in fact, in addition to the reflection mechanism to obtain the tag information, for other ways these tags are not visible!
Let's take a look at the official reflect Structtag section, reflect-the Go programming Language.

Structtag is the alias of the string base type: The type StructTag string rule is that key:"value" it is a key value pair. (What if I don't follow this agreement ?) Of course, but this will lead to the StructTag.Get() method can not parse your refined mark, then you can only implement their own analytic logic, in short you happy.

func (tag StructTag) Get(key string) string

The get () function is used to get the value of the specified key, for example, if there is a token mytag:"X.FLY" , thenGet("mytag") => X.FLY

func (tag StructTag) Lookup(key string) (value string, ok bool)

The Lookup () function is added after Golang 1.7 to determine whether the specified key exists.

Use the example to run an attempt on the Go Playground, where there is no more reflection to unfold.

JSON ' s Tag

This highlights the JSON Struct Tag (1. JSON output is common; 2. Other such as XML ' s TAG can be used and so on.
I want to know what the JSON tag is, where to find it? Go to the official website JSON. The Marshal function is found in the documentation.

The encoding of each struct field can is customized by the format string stored under the "JSON" key in the struct field ' s Tag. The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may is empty in order to specify options without overriding the default field name.
We will find that the JSON encoding process will fetch the tag of each Struct field, take the json value of the key, and then handle it accordingly.

Note Parsing rules: The first string of value must indicate the new field name after overwriting, followed by a comma if there is a resolution option.

For example Name string json:"name,omitempty" , the first string name indicates that the name attribute is changed to name after encoding. Then follow the comma delimiter followed by the Omitempty option.

    1. What if I don't want to overwrite and just want to add an option? Name string json:",omitempty", the direct English comma begins.
    2. Extreme, what if my field name is called Omitempty? Omitempty string json:"omitempty,omitempty", remember that the first string represents the name of the new variable, not the option, so duplicate names are good, not afraid.
Think about it - string json:"-," : - string json:",-" What's the difference?
    1. omitempty: If the value of the field is empty (Defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or String), the field is ignored during the encoding process.
    2. -: Apart directly ignores this field.
    3. string: Converts a field value into a string type in JSON during encoding, only if the field type is string, floating point, Integer, or Boolean.

Other tags

Some of the commonly used struct TAG official list, well known struct tags Golang/go Wiki GitHub.

Reference links

    • Json-the Go Programming Language
    • Reflect-the Go Programming Language
    • Struct types-the Go Programming Language specification
    • String literals-the Go Programming Language specification
    • Reflection-what is the use (s) of tags in Go? -Stack Overflow
    • Tags in Golang–golangspec–medium
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.