Nathan Hanna
Nathan Hanna

Reputation: 4973

How can I access the key of a map without knowing the type of the values?

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

Answers (1)

Thundercat
Thundercat

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

Related Questions