So if I have the following struct in Go:
type Person struct {
name string
age int
}
Given that we don't know what consists of the Person
struct, how could we find out programmatically? I've had a look around and it seems that reflection could be used to do this perhaps?
Even just getting the keys for the struct data would be a start, as type []string
but ideally getting the types back also would be useful.
You can indeed use reflection to do this. You primarily want reflect.TypeOf
, reflect.Type.Field
, reflect.Type.NumField
, and reflect.StructField
Code:
package main
import "fmt"
import "reflect"
type Person struct {
name string
age int
}
func main() {
typ := reflect.TypeOf(Person{})
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
fmt.Println("Field name:", field.Name)
fmt.Println("Field type:", field.Type)
fmt.Println()
}
}
Some notes:
reflect.ValueOf
and pass it a pointer to the struct, followed by a call to Value.Elem()