type User struct {
Name string
Age int64
Hobbys *Hobby
Sex string
}
type Hobby struct {
Cars *Car
Games *Game
}
type Car struct {
Brand string
Color string
Price string
}
type Game struct {
Number int64
Style string
}
func main() {
user := &User{
Name: "张三",
Age: 15,
Hobbys : &Hobby{
Cars:&Car{
Brand : "奔驰",
Color:"白色",
Price:"100万",
},
Games : &Game{
Number:10000,
Style: "街机",
},
},
Sex: "男",
}
traverse(*user)
}
func traverse(a interface{}) {
aValue := reflect.ValueOf(a)
aType := reflect.TypeOf(a)
for i := 0; i < aValue.NumField(); i++ {
aField := aValue.Field(i)
aFieldType := aType.Field(i)
fmt.Printf("%v: %v ", aFieldType.Name, aField.Interface())
if aField.Kind() == reflect.Ptr {
traverse(aField.Interface()) //这个地方要怎么去定义指针类型的结构体去执行递归
}
}
}
试试这个方法 Elem()