Reflect. With reflection, and the "reflect" package, Go programs can read their own data structures. They can print names, values, types, and even associated StructTags.
Though reflection does not yield the fastest—or most readable—code, it is effective and can make some data translation programs possible. It can help with data serialization.
Example. This Go program uses reflection. It imports the "reflect" package and calls reflect.TypeOf, and ValueOf, on a struct instance.
Part 1 We have a type definition of a struct called Animal. Two of the fields have struct tags in backtick-delimited strings.
Part 2 We create an instance of the Animal struct, using the value 100 for Size, "blue" for Color, and true for Alive.
Part 3 We use TypeOf on the instance of the struct, which gives us information about the struct type itself (not the values of an instance).
Part 4 For the StructTag information, we access the Tag field and call Get() to access the parsed key-value pairs.
Part 5 To get values of an instance, we can call reflect.ValueOf and then use methods like FieldByName.
package main
import (
"fmt""reflect"
)
// Part 1: specify struct with public fields and use StructTags for additional information.
type Animal struct {
Size int `left:"test" right:"box"`
Color string `left:"ok" right:"next"`
Alive bool
}
func main() {
// Part 2: create an instance of the struct.
animal := Animal{100, "blue", true}
// Part 3: use TypeOf and loop over the fields with NumField, printing their info.
s := reflect.TypeOf(animal)
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fmt.Println("Field index", i, "=", f.Type)
// Part 4: access values from the StructTag strings.
left := f.Tag.Get("left")
right := f.Tag.Get("right")
fmt.Println(" left/right", "=", left, "/", right)
}
// Part 5: use ValueOf, and print values of fields by their names.
test := reflect.ValueOf(animal)
fmt.Println("Size:", test.FieldByName("Size"))
fmt.Println("Color:", test.FieldByName("Color"))
}Field index 0 = int
left/right = test / box
Field index 1 = string
left/right = ok / next
Field index 2 = bool
left/right = /
Size: 100
Color: blue
Summary. Most Go programs do not need significant amounts of reflection. Reflection use tends to be cumbersome and difficult to maintain. But it can be necessary for data serialization.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.