【发布时间】: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"](反射类型。值不支持索引)
【问题讨论】:
-
test的类型是reflect.Value,不支持索引。如果你知道底层类型是一个地图,你可以使用golang.org/pkg/reflect/#Value.MapIndex。
标签: go