我试图递归地反射(reflect)一个结构,打印出每个字段的类型。如果字段是结构的一部分,我希望能够 识别数组中保存的类型,然后反射(reflect)该类型。
这是一些示例代码
package main
import (
"log"
"reflect"
)
type child struct {
Name *string
Age int
}
type Parent struct {
Name string
Surname *string
Children []*child
PetNames []string
}
func main() {
typ := reflect.TypeOf(Parent{})
log.Printf("This is a : %s", typ.Kind())
for i := 0; i < typ.NumField(); i++ {
p := typ.Field(i)
if !p.Anonymous {
switch p.Type.Kind() {
case reflect.Ptr:
log.Printf("Ptr: %s is a type %s", p.Name, p.Type)
case reflect.Slice:
log.Printf("Slice: %s is a type %s", p.Name, p.Type)
subtyp := p.Type.Elem()
if subtyp.Kind() == reflect.Ptr {
subtyp = subtyp.Elem()
}
log.Printf("\tDereferenced Type%s", subtyp)
default:
log.Printf("Default: %s is a type %s", p.Name, p.Type)
}
}
}
}
输出如下所示:
This is a : struct
Default: Name is a type string
Ptr: Surname is a type *string
Slice: Children is a type []*main.child
Dereferenced Type main.child
Slice: PetNames is a type []string
Dereferenced Type string
当我确定一个字段类型是指针的一部分时,我可以通过调用 subtype.Elem() 来推断类型。
输出是'main.child'
如果我然后尝试反射(reflect) child 使用
subSubType := reflect.TypeOf(subtyp)
log.Printf("%+v", subSubType)
我得到以下信息:
*reflect.rtype
如何使用反射 API 迭代子结构的字段?