我需要解析从深度嵌套的 JSON 对象读取的接口(interface)。我使用以下递归函数来获取数组的大部分内容。
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
“期待表达”是什么意思?
最佳答案
此语法:
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
,所以不需要进一步的类型断言!
关于recursion - 在go中使用递归获取深度嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49625328/