What is the third parameter of a Go struct field?

后端 未结 2 1598
迷失自我
迷失自我 2020-12-03 09:28
type Config struct {
    CommitIndex uint64 `json:\"commitIndex\"`
    // TODO decide what we need to store in peer struct
    Peers []*Peer `json:\"peers\"`
}


        
相关标签:
2条回答
  • 2020-12-03 10:06

    What you are referring to is called a tag, and the Go specification states:

    A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored.

    // A struct corresponding to the TimeStamp protocol buffer.
    // The tag strings define the protocol buffer field numbers.
    struct {
        microsec  uint64 "field 1"
        serverIP6 uint64 "field 2"
        process   string "field 3"
    }
    

    This does nothing at compile time, but is used by different packages when doing runtime reflection on the struct. As Amit already pointed out, the encoding/json package is using it to specify marshalling/unmarshalling behaviour. The same goes with encoding/xml, gopkg.in/mgo.v2/bson, etc.

    The tag string is by convention a space separated string. As stated in the reflect package:

    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.

    0 讨论(0)
  • 2020-12-03 10:22

    It's called a struct tag, they can be parsed using the reflect package at runtime.

    From https://golang.org/ref/spec#Struct_types:

    A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration.

    The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored.

    Some packages that use reflection like json and xml use tags to handle special cases better.

    0 讨论(0)
提交回复
热议问题