mercredi 8 juillet 2020

Go - Traversing nested structs

I have a complex structure of this sort:

type InFoo struct {
    v3 int
}
type Bar struct {
    v1 int
    v2 InFoo
}
type Foo struct {
    A int `tag1:"First Tag" tag2:"Second Tag"`
    B string
    C Bar
}

At runtime, this could be further deeply nested. I wrote a function below to traverse the fields as below:

func main() {
    f := Foo{A: 10, B: "Salutations", C: Bar{v1: 10, v2: InFoo{v3: 20}}}
    fType := reflect.TypeOf(f)
    newexaminer(fType)
}

// recursive traversal
func newexaminer(t reflect.Type) {
    for i := 0; i < t.NumField(); i++ {
        f := t.Field(i)
        fmt.Println(f.Name, f.Type.Kind(), f.Type)
        if f.Type.Kind() == reflect.Struct {
            // recurse if struct
            newexaminer(f.Type)
        }

    }
}

Although this works but I am not sure if there is a better/optimized way to do this. Please suggest!





Aucun commentaire:

Enregistrer un commentaire