mardi 5 décembre 2017

golang recursively reflect both type of field and value

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 reflection

The problem is when I try to extract the value I keep getting panics when I reflect the value on a ptr Value. Is it possible to reflect both the type, and keep passing the value through until I get to the primitives, and at that point print both the field name, type and value?

Here is the code I modified:

    func printType(prefix string, t reflect.Type, v reflect.Value 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)
            // Get value for field
            fieldValue := v.Field(i)

            fmt.Print(prefix, f.Name, " ")
            printType(prefix, f.Type, fieldValue, visited)
        }
    default:
        fmt.Printf("%s) : %s\n", t.Kind(), v)
    }
}

When I run this I get a panic when calling fieldValue := v.Field(i) Any thoughts on how to achieve this?

Thanks





Aucun commentaire:

Enregistrer un commentaire