栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

golang递归反射

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)

游乐场的例子



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/383932.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号