What is the third parameter of a Go struct field?
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.
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.