代码之家  ›  专栏  ›  技术社区  ›  edkeveked

类型反射。值不支持索引

go
  •  -1
  • edkeveked  · 技术社区  · 7 年前

    我有一个泛型类型的数组 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”](类型反射。值不支持索引)

    1 回复  |  直到 7 年前
        1
  •  2
  •   Cerise Limón    7 年前

    如果 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)) 
     }