golang递归反射

golang递归反射,第1张

golang递归反射

这是一种方法。

func printType(prefix string, t reflect.Type, 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) fmt.Print(prefix, f.Name, " ") printType(prefix, f.Type, visited)        }    default:        fmt.Printf("%s)n", t.Kind())    }}func main() {    printType("", reflect.TypeOf(Parent{}), make(map[reflect.Type]bool))}

Parent {}的输出具有以下类型:

type child struct {    Name *string    Age  int}type Parent struct {    Name     string    Surname  *string    Children []*child    PetNames []string    Parents  [2]*Parent    child}

是:

main.Parent (struct with 6 fields)    Name string (string)    Surname *string (ptr to string)    Children []*main.child (slice of ptr to struct with 2 fields)        Name *string (ptr to string)        Age int (int)    PetNames []string (slice of string)    Parents [2]*main.Parent (array with 2 elements of ptr to struct with 6 fields)    child main.child (struct with 2 fields)

游乐场的例子



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4947209.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-13
下一篇 2022-11-13

发表评论

登录后才能评论

评论列表(0条)

保存