[英]Golang type assertion for list of items
我調用一個API,它返回一個字典(地圖),其中有一個項目列表作為值。
例如:
result= {'outputs':[{'state':'md','country':'us'}, {'state':'ny','country':'ny'}]}
上面的數據是用python表示的數據。
在Python中,我直接使用result ['outputs'] [0]訪問列表中的元素列表。
在Golang中,相同的API返回數據,但是當我嘗試以result ['outputs'] [0]訪問數據時
得到這個錯誤:
invalid operation: result["outputs"][0] (type interface {} does not support indexing)
看起來我需要進行類型轉換,應該使用什么類型進行轉換,我嘗試過
result["outputs"][0].(List)
result["outputs"][0].([])
但兩者都給我帶來了一個錯誤。
我檢查了返回項目的類型,它就是它-[] interface {}
我的類型轉換應該是什么?
您將值的類型寫為[]interface{}
,然后執行類型斷言來聲明該類型。
還要注意,您首先必須輸入assert,然后再進行索引,例如:
outputs := result["outputs"].([]interface{})
firstOutput := outputs[0]
還要注意, firstOutput
的(靜態)類型將再次是interface{}
。 要訪問其內容,您將需要另一種類型聲明,最有可能是map[string]interface{}
或map[interface{}]interface{}
。
如果可以的話,請使用結構為數據建模,這樣就不必進行“類型斷言廢話”了。
還請注意,有第3方庫支持在諸如您的動態對象內進行輕松的“導航”。 首先,有github.com/icza/dyno
(披露:我是作者)。
使用dyno
,獲得第一個輸出將像:
firstOutput, err := dyno.Get(result, "outputs", 0)
獲取第一個輸出的國家:
country, err := dyno.Get(result, "outputs", 0, "country")
您還可以“重用”以前查找的值,如下所示:
firstOutput, err := dyno.Get(result, "outputs", 0)
// check error
country, err := dyno.Get(firstOutput, "country")
// check error
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.