In Golang, we use Tags
as metadata to provide for each field in a struct. This information is made available using reflection.
This is typically used by packages that transform data from one form to another. For example, we can use Tags
to encode/decode JSON data or read and write from a DB.
Let’s see an example.
package mainimport "fmt"type Employee struct {Id int64 `db:"id"`Firstname string `db:"firstname"`Lastname string `db:"lastname"`}type EmpJson struct {Id int64 `json:"id"`Firstname string `json:"firstname"`Lastname string `json:"lastname"`}
The above code snippet defines two structs. The first struct, Employee
, defines the tags with the prefix db
for each field. The second struct, EmpJson
, defines the tags with the prefix json
for each field.
As we can see, the tag is defined in a typical key:value
manner. The key is usually the package name for which the value is. That is, the fields with the tags as json:"***"
are to be used by the package json
. The fields with the tags as db:"***"
are to be used by the db package.
We can add custom tags, and we use the reflect
package to access these in our code.
package mainimport ("fmt""reflect")func main() {type Me struct {Firstname string `mytag:"FirstName"`Lastname string `mytag:"LastName"`}m := Me{"Anjana", "Shankar"}t := reflect.TypeOf(m)for _, fieldName := range []string{"Firstname", "Lastname"} {field, found := t.FieldByName(fieldName)if !found {continue}fmt.Printf("\nField: Me.%s\n", fieldName)fmt.Printf("\tWhole tag value : %q\n", field.Tag)fmt.Printf("\tValue of 'mytag': %q\n", field.Tag.Get("mytag"))}}
Tags can be used by a package that it is meant for. It is otherwise totally ignored.