-2

I tried writing this:

func KeyExists(m map[interface{}]interface{}, k interface{}) bool {
    if _, ok := m[k]; ok {
        return true
    }
    return false
}

When trying to run this with an m[int]int, I get:

cannot use xxx (type map[int]int) as type map[interface {}]interface {} in argument to KeyExists

Why? From this: How do you make a function accept multiple types in go? I infer that interface{} should work here.

The error message is half helpful and half annoying, since it states I cannot do something but not why.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Tommy
  • 12,588
  • 14
  • 59
  • 110

1 Answers1

1

Map types in Go are not covariant, and therefore not assignment compatible. Moreover, the empty interface, interface{}, does not provide generics. In Go v1, your KeyExists function must be implemented for each concrete map type you wish to inspect.

Less formally, given a map of type map[int]int, it is not possible to assign to a map whose key or element types are dissimilar, such as map[interface{}]interface{}. This holds even if the underlying key or element types are themselves mutually assignable (e.g. it is possible to assign a value of type int to a value of type interface{}).

Note that you can assign any map to a value of type interface{} (example), because all types implement the empty interface. Such assignments are permitted according to the language spec's rules on assignability. However, this is unlikely to be helpful.

Cosmic Ossifrage
  • 4,977
  • 29
  • 30