This is a creation in Article, where the information may have evolved or changed.
When working with JSON-formatted strings, it is often seen that when declaring a struct structure, the right side of the property is also surrounded by millet dots. Shaped like:
1 2 3 4 |
type User struct {
UserId int `json: "user_id" bson: "user_id" `
UserName string `json: "user_name" bson: "user_name" `
}
|
What is the content of this millet spot used for?
struct member variable label (TAG) description
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 just a little bit more. The content of millet dot, called tag in Golang, when converted to other data format, will use the specific field as the key value. For example, the previous example turns into JSON format:
1 2 3 4 |
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.
struct member variable tag (tag) gets
So when we need to encapsulate some of the operation, 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:
1 2 3 4 |
t := reflect.TypeOf(u)
field := t.Elem().Field( 0 )
fmt.Println(field.Tag.Get( "json" ))
fmt.Println(field.Tag.Get( "bson" ))
|
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}