Ano*_*who 0 recursion types go
我需要解析从深度嵌套的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{})
}
}
}
Run Code Online (Sandbox Code Playgroud)
这给出了该return行的错误:
syntax error: unexpected return, expecting expression
Run Code Online (Sandbox Code Playgroud)
"期待表达"是什么意思?
这个语法:
if v.(type) == map[string]interface{} { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
是无效的.您无法与类型进行比较,只能与值进行比较.
您想要的可以使用类型开关来解决,其中案例确实是类型:
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
}
Run Code Online (Sandbox Code Playgroud)
另请注意,如果在switch关键字后使用短变量声明,则每个case使用的变量类型都是您在其中指定的case,因此不需要进一步的类型断言!