Golang < turn >go language struct tag Introduction

Source: Internet
Author: User


First, Tag description

Introduce the words "(anti-quotation marks): Anti-quotation marks are used to create native string literals , which may consist of multiple lines (no escape sequences are supported), and native string literals are used to write multi-line messages, HTML, and regular expressions.

When working with JSON-formatted strings, you will often see the declaration of a struct structure, and the right side of the property is also surrounded by anti-quotes. As follows:

1234 type user struct {      userid   int    ' JSON: "user_id" bson: "user_id"      username string ' JSON: "user_name" bson: "user_name" }

To more detailed understanding of this, to understand the basis of the Golang, in the Golang, the name is recommended is the hump way, and in the first letter case has a special grammatical meaning: Outside the package can not be referenced. However, it is often necessary to interact with other systems, such as turning into JSON format, storing to MongoDB, and so on. At this point, using the property name as the key value may not necessarily conform to the project requirements.

So it's a lot more. The content of the anti-quote , called the tag in Golang, when converted to other data formats, will use the specific field as the key value. For example, the previous example turns into JSON format:

1234 u := &User{UserId: 1, UserName: "tony"}j, _ := json.Marshal(u)fmt.Println(string(j))// 输出内容:{"user_id":1,"user_name":"tony"}

If the label description is not added in the attribute, the output is:{"UserId":1,"UserName":"Tony"}

You can see that the key value is made directly from the struct's property name.

There is also a Bson statement, which is used to store data in MongoDB.

Second, tag access

So when we need to encapsulate some of the operations, need to use the contents of the tag, how to get it? This way you can use the methods in the reflection package (reflect) to get:

123456789101112131415161718192021222324 package main  import (    "encoding/json"    "fmt"    "reflect")  func main() {    type User struct {        UserId   int    `json:"user_id" bson:"user_id"`        UserName string `json:"user_name" bson:"user_name"`    }    // 输出json格式    u := &User{UserId: 1, UserName: "tony"}    j, _ := json.Marshal(u)    fmt.Println(string(j)) // 输出内容:{"user_id":1,"user_name":"tony"}      // 获取tag中的内容    t := reflect.TypeOf(u)    field := t.Elem().Field(0)    fmt.Println(field.Tag.Get("json")) // 输出:user_id    fmt.Println(field.Tag.Get("bson")) // 输出:user_id}

123456789101112131415161718 package mainimport (    "fmt"    "reflect" // 这里引入reflect模块) type User struct {    Name   string "user name" //这引号里面的就是tag    Passwd string "user passsword"} func main() {    user := &User{"chronos", "pass"}    s := reflect.TypeOf(user).Elem() //通过反射获取type定义    for i := 0; i < s.NumField(); i++ {        fmt.Println(s.Field(i).Tag) //将tag输出出来    }}


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.