首页 > 解决方案 > Go - 遍历嵌套结构

问题描述

我有这种复杂的结构:

type InFoo struct {
    v3 int
}
type Bar struct {
    v1 int
    v2 InFoo
}
type Foo struct {
    A int
    B string
    C Bar
}

在运行时,这可以进一步深入嵌套。我在下面编写了一个函数来遍历以下字段:

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)
        }

    }
}

虽然这可行,但我不确定是否有更好/优化的方法来做到这一点。请建议!

func main() {
    f := Foo{A: 10, B: "Salutations", C: Bar{v1: 10, v2: InFoo{v3: 20}}}
    jsonRes, err := json.Marshal(f)
    if err != nil {
        fmt.Println(err)
    }

    var iRes interface{}

    err = json.Unmarshal(jsonRes, &iRes)
    if err != nil {
        fmt.Println(err)
    }
    res := iRes.(map[string]interface{})

    for _, v := range res {

        fmt.Println(v)
        // need to type assert v again to extract map keys/values
    }
} 

游乐场: https: //play.golang.org/p/_TXrRGxpIyx

这是遍历结构的惯用方式吗?看起来这仍然需要多个断言和循环才能到达最内部的字段。这是解析复杂 json 文档的理想方法还是有更好的方法来做到这一点

标签: goreflection

解决方案


推荐阅读