At some point in your day to day hacking life, getting the Struct fields and values may come in handy.
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
ID string
}
type Robot struct {
Person
IP string
}
func main() {
p := Person{"john", "12345"}
r := Robot{p, "1.1.1.1"}
v := reflect.ValueOf(&r).Elem()
for i := 0; i < v.NumField(); i++ {
if v.Field(i).Kind() == reflect.Struct {
v2 := reflect.ValueOf(v.Field(i).Interface())
for j := 0; j < v2.NumField(); j++ {
fmt.Printf("%s.%s %s = %v\n",
v.Field(i).Type(),
v2.Type().Field(j).Name,
v2.Field(j).Type(),
v2.Field(j).Interface(),
)
}
continue
}
fmt.Printf("%s %s = %v\n",
v.Type().Field(i).Name,
v.Field(i).Type(),
v.Field(i).Interface(),
)
}
}
Output:
main.Person.Name string = john
main.Person.ID string = 12345
IP string = 1.1.1.1