structs
are used to collect multiple pieces of information together in one unit. When you read this information from systems such as databases, or APIs, you can use struct tags
to control how this information is assigned to the fields of a struct
A tag for a field allows you to attach meta-information to the field which can be acquired using reflection.
A struct tag looks like this, with the tag offset with backtick `
characters:
type User struct {
Name string `json:"name" xml:"name"`
}
Other Go code is then capable of examining these structs and extracting the values assigned to specific keys it requests. Struct tags have no effect on the operation of your code without additional code that examines them.
json
- used by the encoding/json
package, detailed at json.Marshal()
xml
- used by the encoding/xml
package, detailed at xml.Marshal()
bson
- used by gobson, detailed at bson.Marshal()
; also by the mongo-go driver, detailed at bson package docprotobuf
- used by github.com/golang/protobuf/proto
, detailed in the package docyaml
- used by the gopkg.in/yaml.v2
package, detailed at yaml.Marshal()
db
- used by the github.com/jmoiron/sqlx
package; also used by github.com/go-gorp/gorp
packageorm
- used by the github.com/astaxie/beego/orm
package, detailed at Models – Beego ORMgorm
- used by gorm.io/gorm
, examples can be found in their docsvalid
- used by the github.com/asaskevich/govalidator
package, examples can be found in the project pagedatastore
- used by appengine/datastore
(Google App Engine platform, Datastore service), detailed at Propertiesschema
- used by github.com/gorilla/schema
to fill a struct
with HTML form values, detailed in the package docasn1
- used by the encoding/asn1
package, detailed at asn1.Marshal()
and asn1.Unmarshal()
csv
- used by the github.com/gocarina/gocsv
packageenv
- used by the github.com/caarlos0/env
package