Handle maps with same key type but different value type

Though maps and slices in go are generic themselves, they are not covariant (nor could they be, since interfaces aren’t generics). It’s part of working with a language that doesn’t have generics, you will have to repeat some things.

If you really just need to get the keys of any old map, you can use reflection to do so:

func useKeys(m interface{}) {
    v := reflect.ValueOf(m)
    if v.Kind() != reflect.Map {
        fmt.Println("not a map!")
        return
    }

    keys := v.MapKeys()
    fmt.Println(keys)
}

Leave a Comment