在golang中,我想通过结构体递归地反映,获取字段的名称、类型和值。
这里的代码帮助我反思golang递归反射 https://stackoverflow.com/questions/47624318/golang-recurisive-reflection/47625992?noredirect=1#comment82247395_47625992
问题是,当我尝试提取值时,当我将该值反映在 ptr 值上时,我会不断出现恐慌。
是否可以反映类型,并继续传递值,直到到达基元,然后打印字段名称、类型和值?
这是我修改的代码:
func printType(prefix string, t reflect.Type, v reflect.Value visited map[reflect.Type]bool) {
// Print the name of this type with opening ( for description.
fmt.Printf("%s (", t)
// Traverse elements, adding to description as we go.
elems:
for {
switch t.Kind() {
case reflect.Ptr:
fmt.Print("ptr to ")
case reflect.Slice:
fmt.Print("slice of ")
case reflect.Array:
fmt.Printf("array with %d elements of ", t.Len())
default:
break elems
}
t = t.Elem()
}
// Print the kind of the type and the closing ) of the description.
// In the case of a struct, we print the names of the fields and recurse.
switch t.Kind() {
case reflect.Struct:
fmt.Printf("struct with %d fields)\n", t.NumField())
if visited[t] {
// Don't blow up on recursive type definition.
break
}
visited[t] = true
prefix += " "
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
// Get value for field
fieldValue := v.Field(i)
fmt.Print(prefix, f.Name, " ")
printType(prefix, f.Type, fieldValue, visited)
}
default:
fmt.Printf("%s) : %s\n", t.Kind(), v)
}
}
当我运行这个时,我在调用 fieldValue := v.Field(i) 时感到恐慌
关于如何实现这一目标有什么想法吗?
Thanks