jeudi 8 juillet 2021

Reading nested structure in golang using reflect

I write a recursive function that iterate over deep nested struct like the following:

type Container struct {
    Name string
    Items []Item
}

type Item struct {
    Name string
    Info Info
    Vals []string
}
// recursively reads nested struct, prints string values
func ReadStruct(st interface{}) {
    val := reflect.ValueOf(st).Elem()
    for i := 0; i < val.NumField(); i++ {
        fmt.Println(val.Type().Field(i).Type.Kind())
        switch val.Type().Field(i).Type.Kind() {
        case reflect.Struct:
            ReadStruct(val.Field(i)) // panic: call of reflect.Value.Elem on struct Value
        case reflect.Slice:
            // How to iterate over the reflect.Slice? 
        case reflect.String:
            fmt.Printf("%v=%v", val.Type().Field(i).Name, val.Field(i))
        }
    }
  

how to get access to inner objects (slices, structs) to work with them using reflect? to iterate over slice i tried to use:

for i:= 0; i < val.Field(i).Slice(0, val.Field(i).Len()); i++ { //error: reflect.Value doesnt support indexing
//some work

}





Aucun commentaire:

Enregistrer un commentaire