【发布时间】:2015-12-28 11:54:06
【问题描述】:
我想递归地反映结构类型和值,但它失败了。我不知道如何递归地传递子结构。
以下错误。
panic: reflect: NumField of non-struct type
goroutine 1 [running]:
reflect.(*rtype).NumField(0xc0b20, 0xc82000a360)
/usr/local/go/src/reflect/type.go:660 +0x7b
我有两个结构 Person 和 Name
type Person struct {
Fullname NameType
Sex string
}
type Name struct {
Firstname string
Lastname string
}
我在main中定义Person,并用递归函数显示结构体。
person := Person{
Name{"James", "Bound"},
"Male",
}
display(&person)
display 函数递归显示结构体。
func display(s interface{}) {
reflectType := reflect.TypeOf(s).Elem()
reflectValue := reflect.ValueOf(s).Elem()
for i := 0; i < reflectType.NumField(); i++ {
typeName := reflectType.Field(i).Name
valueType := reflectValue.Field(i).Type()
valueValue := reflectValue.Field(i).Interface()
switch reflectValue.Field(i).Kind() {
case reflect.String:
fmt.Printf("%s : %s(%s)\n", typeName, valueValue, valueType)
case reflect.Int32:
fmt.Printf("%s : %i(%s)\n", typeName, valueValue, valueType)
case reflect.Struct:
fmt.Printf("%s : it is %s\n", typeName, valueType)
display(&valueValue)
}
}
}
【问题讨论】:
-
查看此链接以获取解决方案:stackoverflow.com/questions/25047424/…
-
如果你不想自己做,或者想看看别人是怎么做的,看看这台非常漂亮的 Go 打印机 github.com/davecgh/go-spew
标签: go go-reflect