【问题标题】:Using recursion to get the deeply nested struct in go使用递归获取深度嵌套的结构
【发布时间】:2018-09-12 11:59:41
【问题描述】:

我需要解析从深度嵌套的 JSON 对象读取的接口。我使用以下递归函数来获取大部分数组。

func arrayReturn(m map[string]interface{}) []interface{} {
    for _, v:= range m {
        if v.(type) == map[string]interface{} {
            return arrayReturn(v.(map[string]interface{}))
        }
        if v.(type) == string {
            return v.([]interface{})
        } 
    }
}

return 行出现此错误:

syntax error: unexpected return, expecting expression

“期待表达”是什么意思?

【问题讨论】:

    标签: recursion go types


    【解决方案1】:

    这个语法:

    if v.(type) == map[string]interface{} { /* ... */ }
    

    无效。无法与类型进行比较,只能与值进行比较。

    您想要的可以使用type switch 解决,其中的案例确实是类型:

    func arrayReturn(m map[string]interface{}) []interface{} {
        for _, v := range m {
            switch v2 := v.(type) {
            case map[string]interface{}:
                return arrayReturn(v2)     // v2 is of type map[string]interface{}
            case []interface{}:
                return v2                  // v2 is of type []interface{}
            }
        }
        return nil
    }
    

    还请注意,如果您在 switch 关键字之后使用短变量声明,则在每个 case 中使用的变量类型将是您在 case 中指定的类型,因此不需要进一步的类型断言!

    【讨论】:

      猜你喜欢
      • 2017-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 2015-08-04
      • 2020-03-19
      • 1970-01-01
      • 2021-07-18
      相关资源
      最近更新 更多