What is the third parameter of a Go struct field?

后端 未结 2 1606
迷失自我
迷失自我 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: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.

提交回复
热议问题