【发布时间】:2017-12-06 08:21:50
【问题描述】:
在 golang 中,我想通过一个结构递归地反映,获取字段的名称、类型和值。
这里的代码帮我反映golang recurisive reflection
问题是当我尝试提取值时,当我将值反映在 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) 时会感到恐慌 关于如何实现这一目标的任何想法?
谢谢
【问题讨论】:
标签: go reflection