golang recursively reflect both type of field and value

前端 未结 1 454
渐次进展
渐次进展 2021-01-27 14:20

In golang, I want to recursively reflect through a struct, getting the name of the field, it\'s type and the value.

The code here helped me reflect golang recurisive r

相关标签:
1条回答
  • 2021-01-27 14:40

    Try this:

    func printValue(prefix string, v reflect.Value, visited map[interface{}]bool) {
    
        fmt.Printf("%s: ", v.Type())
    
        // Drill down through pointers and interfaces to get a value we can print.
        for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
            if v.Kind() == reflect.Ptr {
                // Check for recursive data
                if visited[v.Interface()] {
                    fmt.Println("visted")
                    return
                }
                visited[v.Interface()] = true
            }
            v = v.Elem()
        }
    
        switch v.Kind() {
        case reflect.Slice, reflect.Array:
            fmt.Printf("%d elements\n", v.Len())
            for i := 0; i < v.Len(); i++ {
                fmt.Printf("%s%d: ", prefix, i)
                printValue(prefix+"   ", v.Index(i), visited)
            }
        case reflect.Struct:
            t := v.Type() // use type to get number and names of fields
            fmt.Printf("%d fields\n", t.NumField())
            for i := 0; i < t.NumField(); i++ {
                fmt.Printf("%s%s: ", prefix, t.Field(i).Name)
                printValue(prefix+"   ", v.Field(i), visited)
            }
        case reflect.Invalid:
            fmt.Printf("nil\n")
        default:
            fmt.Printf("%v\n", v.Interface())
        }
    }
    

    Because it's possible to get the type from a value, there's no need to pass types to the print function.

    playground example

    0 讨论(0)
提交回复
热议问题