In the Go Language Specification, it mentions a brief overview of tags:
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 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 is a very short explanation IMO, and I was wondering if anyone could provide me with what use these tags would be?
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
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 :
A tag for a field allows you to attach meta-information to the field which can be acquired using reflection. Usually it is used to provide transformation info on how a struct field is encoded to or decoded from another format (or stored/retrieved from a database), but you can use it to store whatever meta-info you want to, either intended for another package or for your own use.
As mentioned in the documentation of
reflect.StructTag
, by convention the value of a tag string is a space-separated list ofkey:"value"
pairs, for example:The
key
usually denotes the package that the subsequent"value"
is for, for examplejson
keys are processed/used by theencoding/json
package.If multiple information is to be passed in the
"value"
, usually it is specified by separating it with a comma (','
), e.g.Usually a dash value (
'-'
) for the"value"
means to exclude the field from the process (e.g. in case ofjson
it means not to marshal or unmarshal that field).Example of accessing your custom tags using reflection
We can use reflection (
reflect
package) to access the tag values of struct fields. Basically we need to acquire theType
of our struct, and then we can query fields e.g. withType.Field(i int)
orType.FieldByName(name string)
. These methods return a value ofStructField
which describes / represents a struct field; andStructField.Tag
is a value of typeStructTag
which describes / represents a tag value.Previously we talked about "convention". This convention means that if you follow it, you may use the
StructTag.Get(key string)
method which parses the value of a tag and returns you the"value"
of thekey
you specify. The convention is implemented / built into thisGet()
method. If you don't follow the convention,Get()
will not be able to parsekey:"value"
pairs and find what you're looking for. That's also not a problem, but then you need to implement your own parsing logic.Also there is
StructTag.Lookup()
(was added in Go 1.7) which is "likeGet()
but distinguishes the tag not containing the given key from the tag associating an empty string with the given key".So let's see a simple example:
Output (try it on the Go Playground):
GopherCon 2015 had a presentation about struct tags called:
The Many Faces of Struct Tags (slide) (and a video)
Here is a list of commonly used tag keys:
json
- used by theencoding/json
package, detailed atjson.Marshal()
xml
- used by theencoding/xml
package, detailed atxml.Marshal()
bson
- used by gobson, detailed atbson.Marshal()
protobuf
- used bygithub.com/golang/protobuf/proto
, detailed in the package docyaml
- used by thegopkg.in/yaml.v2
package, detailed atyaml.Marshal()
db
- used by thegithub.com/jmoiron/sqlx
package; also used bygithub.com/go-gorp/gorp
packageorm
- used by thegithub.com/astaxie/beego/orm
package, detailed at Models – Beego ORMgorm
- used by thegithub.com/jinzhu/gorm
package, examples can be found in their doc: Modelsvalid
- used by thegithub.com/asaskevich/govalidator
package, examples can be found in the project pagedatastore
- used byappengine/datastore
(Google App Engine platform, Datastore service), detailed at Propertiesschema
- used bygithub.com/gorilla/schema
to fill astruct
with HTML form values, detailed in the package docasn
- used by theencoding/asn1
package, detailed atasn1.Marshal()
andasn1.Unmarshal()
csv
- used by thegithub.com/gocarina/gocsv
package