Retrieving Field Name & Value in Struct
We can use reflect package for retrieving field name and value dynamically from a struct.
package main
import (
"fmt"
"reflect"
)
type Foo struct {
aa string
ff string
}
func main() {
foo := Foo{"x", "y"}
t := reflect.TypeOf(foo) // => Returns a type Type
fmt.Println(t.Field(0).Name) // => "aa"
r := reflect.ValueOf(foo)
fmt.Println(r.Field(0)) // => "x"
fmt.Println(r.FieldByName("aa")) // => "x"
}
In this way we can save the name to a variable and use it to retrieve value:
field := t.Field(0).Name
value := r.FieldByName(field)
An example in play