英文:
How should I use type map[string]interface {} in golang
问题
我正在尝试从API中检索数据。当我从API获取数据时:
result, _ := s.GetCases() // 通过API获取案例
fmt.Println(reflect.TypeOf(result.Records[0]["Cases"]))
它显示result.Records[0]["Cases"]的类型是map[string]interface {}
然而,显然我不能直接将其作为一个map使用。因为:
fmt.Println(reflect.TypeOf(result.Records[0]["Cases"]["Id"]))
这将导致编译器错误:
无效操作:无法索引result.Records[0]["Cases"](类型为interface{}的映射索引表达式)
请问我应该如何在Go语言中使用这种类型?
英文:
I am trying to retrieve data from api. When I get the data from api:
result, _ := s.GetCases() // get cases via api
fmt.Println(reflect.TypeOf(result.Records[0]["Cases"]))
It shows the type of result.Records[0]["Cases"] is map[string]interface {}
However, apparently I can't directly use this one as a map. Since:
fmt.Println(reflect.TypeOf(result.Records[0]["Cases"]["Id"]))
This will cause compiler error:
> invalid operation: cannot index result.Records[0]["Cases"] (map index
> expression of type interface{})
May I know how should I use this type in golang?
答案1
得分: 1
值的类型是interface{}
,根据反射的输出,该接口中包含一个map[string]interface{}
的值。因此,你需要使用类型断言来获取接口中存储的实际值:
fmt.Println(reflect.TypeOf(result.Records[0]["Cases"].(map[string]interface{})["Id"]))
英文:
The value is of type interface{}
, and based on the output of reflection, that interface has a map[string]interface{}
value in it. So, you have to get the actual value stored in the interface using a type assertion:
fmt.Println(reflect.TypeOf(result.Records[0]["Cases"].(map[string]interface{})["Id"]))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论