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.
This Go program uses reflection. It imports the "reflect" package and calls reflect.TypeOf
, and ValueOf
, on a struct
instance.
struct
called Animal. Two of the fields have struct
tags in backtick-delimited strings.struct
, using the value 100 for Size
, "blue" for Color, and true for Alive.TypeOf
on the instance of the struct
, which gives us information about the struct
type itself (not the values of an instance).StructTag
information, we access the Tag field and call Get()
to access the parsed key-value pairs.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
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.