【问题标题】:type reflect.Value does not support indexing类型 reflect.Value 不支持索引
【发布时间】:2018-10-29 00:45:36
【问题描述】:

我有一个泛型类型 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]

无效操作:test["id"](反射类型。值不支持索引)

【问题讨论】:

标签: go


【解决方案1】:

如果 historyInterface 是通过将 JSON 解组为 interface{} 而创建的,则映射的类型为 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)) 
 }

【讨论】:

  • 我有以下错误:interfaceconversion: interface {} is bson.M, not map[string]interface {},所以我改用bson.M接口
猜你喜欢
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 2018-09-16
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
相关资源
最近更新 更多