项目列表的 Golang 类型断言

Golang type assertion for list of items

我正在调用一个 API,它 returns 一个以项目列表作为值的字典(地图)。

例如:-

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

以上数据就是python中数据的表示方式。

在Python中,我直接使用result['outputs'][0]访问列表中的元素列表

在 Golang 中,相同的 API returns 数据但是当我尝试访问数据时 ['outputs'][0]

得到这个错误:-

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

看来我需要做一个类型转换,我应该用什么来类型转换, 我试过了

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

但两者都给我一个错误。

我检查了退回商品的类型,就是这个 - []interface {}

我的类型转换应该是什么?

您写的值的类型是 []interface{},因此请执行 type assertion 断言该类型。

另请注意,您必须先输入 assert,然后再输入索引,例如:

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

firstOutput := outputs[0]

另请注意,firstOutput 的(静态)类型将再次变为 interface{}。要访问其内容,您将需要另一个类型断言,很可能是 map[string]interface{}map[interface{}]interface{}.

如果可以,请使用结构对数据建模,这样您就不必这样做 "type assertion nonsense"。

另请注意,有第 3 方库支持简单的 "navigation" 内部动态对象,例如您的对象。其中之一是 github.com/icza/dyno(披露:我是作者)。

使用 dyno,得到第一个输出就像:

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

获取第一个输出的国家:

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

您还可以 "reuse" 之前查找的值,如下所示:

firstOutput, err := dyno.Get(result, "outputs", 0)
// check error
country, err := dyno.Get(firstOutput, "country")
// check error