如何在不知道值类型的情况下访问映射键?

如何在不知道值类型的情况下访问映射键?

问题描述:

If I have a map in an interface variable and want to access a key, but do not know what type the values of the map will be, how can I access that key?

Here is an example on go playground

To solve my problem I need to figure out how to make the main function run without errors.

如果我在接口变量中有映射并且想要访问键,但不知道值的类型 地图的位置,我该如何访问该键? p>

这里是去游乐场的一个例子 p>

要解决我的问题,我需要弄清楚如何使主函数正确运行。 p> div >

Use the reflect package to operate on arbitrary map types:

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
}