What are the use(s) for tags in Go?

前端 未结 3 2072
鱼传尺愫
鱼传尺愫 2020-11-22 01:38

In the Go Language Specification, it mentions a brief overview of tags:

A field declaration may be followed by an optional string literal tag, whic

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 02:25

    Here is a really simple example of tags being used with the encoding/json package to control how fields are interpreted during encoding and decoding:

    Try live: http://play.golang.org/p/BMeR8p1cKf

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    type Person struct {
        FirstName  string `json:"first_name"`
        LastName   string `json:"last_name"`
        MiddleName string `json:"middle_name,omitempty"`
    }
    
    func main() {
        json_string := `
        {
            "first_name": "John",
            "last_name": "Smith"
        }`
    
        person := new(Person)
        json.Unmarshal([]byte(json_string), person)
        fmt.Println(person)
    
        new_json, _ := json.Marshal(person)
        fmt.Printf("%s\n", new_json)
    }
    
    // *Output*
    // &{John Smith }
    // {"first_name":"John","last_name":"Smith"}
    

    The json package can look at the tags for the field and be told how to map json <=> struct field, and also extra options like whether it should ignore empty fields when serializing back to json.

    Basically, any package can use reflection on the fields to look at tag values and act on those values. There is a little more info about them in the reflect package
    http://golang.org/pkg/reflect/#StructTag :

    By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

提交回复
热议问题