Reputation: 4973
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.
Upvotes: 1
Views: 832
Reputation: 121199
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
}
Upvotes: 3