Reflection Basics
Struct Tags
Struct tags attach metadata that libraries can read through reflection.
Struct Tags
struct_tags_reflect.go
package main
import (
"fmt"
"reflect"
)
type Item struct {
SKU string `json:"sku"`
Count int `json:"count"`
}
func main() {
var fieldIndex =
itemType := reflect.TypeOf(Item{})
field := itemType.Field(fieldIndex)
jsonName := field.Tag.Get("json")
fmt.Println("field_index=", fieldIndex)
fmt.Println("field_name=", field.Name)
fmt.Println("field_type=", field.Type.String())
fmt.Println("json_name=", jsonName)
}
package main
import (
"fmt"
"reflect"
)
type Item struct {
SKU string `json:"sku"`
Count int `json:"count"`
}
func main() {
var fieldIndex =
itemType := reflect.TypeOf(Item{})
field := itemType.Field(fieldIndex)
jsonName := field.Tag.Get("json")
fmt.Println("field_index=", fieldIndex)
fmt.Println("field_name=", field.Name)
fmt.Println("field_type=", field.Type.String())
fmt.Println("json_name=", jsonName)
}
struct tags
Tags are strings attached to fields. Reflection can read them so encoders and validators can follow naming rules.