Using tags

A structure field carries plenty of information, from the field name and index to its tag:

type StructField struct {
Name string
PkgPath string

Type Type // field type
Tag StructTag // field tag string
Offset uintptr // offset within struct, in bytes
Index []int // index sequence for Type.FieldByIndex
Anonymous bool // is an embedded field
}

A reflect.StructField value can be obtained using the reflect.Type methods:

  • Field
  • FieldByName
  • FieldByIndex

They are the same methods used by reflect.Value, but they return different types. The NumField method returns the total number of fields for the structure, allowing us to execute an iteration:

type Person struct {
Name string `json:"name,omitempty" xml:"-"`
Surname string `json:"surname,omitempty" xml:"-"`
}

func main() {
v := reflect.ValueOf(Person{"Micheal", "Scott"})
t := v.Type()
fmt.Println("Type:", t)
for i := 0; i < t.NumField(); i++ {
fmt.Printf("%v: %v ", t.Field(i).Name, v.Field(i))
}
}

A full example is available here: https://play.golang.org/p/nkEADg77zFC.

Tags are really central to reflection because they can store extra information about a field and how other packages behave with it. To add a tag to a field, it needs to be inserted after the field name and type in a string, which should have a key:"value" structure. One field can have multiple tuples in its tag, and each pair is separated by a space. Let's look at a practical example:

type A struct {
Name string `json:"name,omitempty" xml:"-"`
Surname string `json:"surname,omitempty" xml:"-"`
}

This structure has two fields, both with tags, and each tag has two pairs. The Get method returns the value for a specific key:

func main() {
t := reflect.TypeOf(A{})
fmt.Println(t)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
fmt.Printf("%s JSON=%s XML=%s ", f.Name, f.Tag.Get("json"), f.Tag.Get("xml"))
}
}

A full example is available here: https://play.golang.org/p/P-Te8O1Hyyn.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.139.224