类型反映.值不支持索引

  • 本文关键字:不支持 索引 类型 go
  • 更新时间 :
  • 英文 :


我有一个泛型类型interface{}数组,我会检查该数组是否在其JSON对象之一中包含某个值。

history := reflect.ValueOf(historyInterface)
for i := 0; i < history.Len(); i++ {
// here I can get a map object
test := history.Index(i) 
// then I tried to access the id property of the object 
// but here it fails
fmt.Println("test", test["id"].(string)) 
}

以下是每次迭代的测试外观:

first iteration
map[id:5afbff19bf07c79c19ed9af9 date:Saturday, January 21, 2017 9:21 PM certitude:33]
second iteration
map[id:afbff198658487a3e3e376b date:Thursday, March 3, 2016 2:24 PM certitude:30]

无效操作:测试["ID"](类型反映。值不支持索引(

如果通过将 JSON 解编组到interface{}来创建historyInterface,则映射的类型为map[string]interface{}。 使用类型断言获取该类型的映射:

history := reflect.ValueOf(historyInterface)
for i := 0; i < history.Len(); i++ {
test := history.Index(i).Interface().(map[string]interface{})
fmt.Println("test", test["id"].(string)) 
}

同样基于对数据源的假设,应用程序可以使用类型断言而不是反射。

history := historyInterface.([]interface{})
for _, m := range history {
test := m.(map[string]interface{})
fmt.Println("test", test["id"].(string)) 
}

最新更新