How should I use type map[string]interface {} in golang

huangapple go评论77阅读模式
英文:

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"]))

huangapple
  • 本文由 发表于 2023年3月31日 09:48:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75894217.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定