改成这样?
package main
import (
"fmt"
"reflect"
)
func PrintlnFunc(in any) {
fmt.Printf("\033[36;1;4mOutput:\033[0m \033[31;1;4m%v\033[0m\n", in)
}
func SprintfFunc(format string, in ...any) string {
return fmt.Sprintf(format, in...)
}
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 traverse(a interface{}) {
aValue := reflect.ValueOf(a)
aType := reflect.TypeOf(a)
for i := 0; i < aValue.Elem().NumField(); i++ {
aField := aValue.Elem().Field(i)
aFieldType := aType.Elem().Field(i)
PrintlnFunc(SprintfFunc("%v: %v ", aFieldType.Name, aField.Interface()))
if aField.Kind() == reflect.Ptr {
traverse(aField.Interface()) //这个地方要怎么去定义指针类型的结构体去执行递归
}
}
}
func main() {
user := &User{
Name: "张三",
Age: 15,
Hobbys: &Hobby{
Cars: &Car{
Brand: "奔驰",
Color: "白色",
Price: "100万",
},
Games: &Game{
Number: 10000,
Style: "街机",
},
},
Sex: "男",
}
traverse(user)
}
输出:
Output: Name: 张三
Output: Age: 15
Output: Hobbys: &{0xc0000981b0 0xc0000a0030}
Output: Cars: &{奔驰 白色 100万}
Output: Brand: 奔驰
Output: Color: 白色
Output: Price: 100万
Output: Games: &{10000 街机}
Output: Number: 10000
Output: Style: 街机
Output: Sex: 男