doukanwen4114 2018-08-11 19:52
浏览 66
已采纳

项目列表的Golang类型断言

Im calling a API and it returns a dictionary(map) with a list of items as values.

For ex:-

result= {'outputs':[{'state':'md','country':'us'}, {'state':'ny','country':'ny'}]}

The above data is how the data represented in python.

In Python, I directly use result['outputs'][0] to access the list of elements in the list.

In Golang, the same API returns the data but when I try to access the data as result['outputs'][0]

Get this error:-

invalid operation: result["outputs"][0] (type interface {} does not support indexing)

Looks like I need to do a type conversion, what should I use to type convert, I tried this

result["outputs"][0].(List)
result["outputs"][0].([])

but both throws me an error.

I checked the type of the returned item and this is it - []interface {}

What should be my type conversion?

  • 写回答

1条回答 默认 最新

  • duanshan1511 2018-08-11 20:13
    关注

    You wrote the type of the value is []interface{}, so then do a type assertion asserting that type.

    Also note that you first have to type assert, and index later, e.g.:

    outputs := result["outputs"].([]interface{})
    
    firstOutput := outputs[0]
    

    Also note that the (static) type of firstOutput will again be interface{}. To access its content, you will need another type assertion, most likely a map[string]interface{} or a map[interface{}]interface{}.

    If you can, model your data with structs so you don't have to do this "type assertion nonsense".

    Also note that there are 3rd party libs that support easy "navigation" inside dynamic objects such as yours. For one, there's github.com/icza/dyno (disclosure: I'm the author).

    Using dyno, getting the first output would be like:

    firstOutput, err := dyno.Get(result, "outputs", 0)
    

    To get the country of the first output:

    country, err := dyno.Get(result, "outputs", 0, "country")
    

    You can also "reuse" previously looked up values, like this:

    firstOutput, err := dyno.Get(result, "outputs", 0)
    // check error
    country, err := dyno.Get(firstOutput, "country")
    // check error
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog