如果我在接口(interface)变量中有一个映射并想访问一个键,但不知道映射的值是什么类型,我该如何访问该键?
Here是 go playground 上的一个例子
为了解决我的问题,我需要弄清楚如何让主函数无错误地运行。
最佳答案
使用 reflect对任意 map 类型进行操作的包:
func GetMapKey(reference interface{}, key string) (interface{}, error) {
m := reflect.ValueOf(reference)
if m.Kind() != reflect.Map {
return nil, errors.New("not a map")
}
v := m.MapIndex(reflect.ValueOf(key))
if !v.IsValid() {
return nil, errors.New("The " + key + " key was not present in the map")
}
return v.Interface(), nil
}
关于go - 如何在不知道值类型的情况下访问 map 的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48916313/