gogo-interfacego-map

Golang map with any key type and any value type


can i create in golang a map with any key type and any value type ? , something like :

dict1 := map[interface]interface{}

Thanks a lot !


Solution

  • From the language spec for the key type:

    The comparison operators == and != must be fully defined for operands of the key type;

    So most types can be used as a key type, however:

    Slice, map, and function values are not comparable

    and thus cannot be used as a map-key.

    The value type can be any or (any or interface{}) type.

    type mytype struct{}
    type ss []string
    
    _ = make(map[interface{}]interface{}) // this works...
    _ = make(map[any]any)                 // ... semantically the same
    _ = make(map[mytype]any)              // even a struct
    
    _ = make(map[ss]any) // FAILS: invalid map key type ss
    

    https://go.dev/play/p/OX_utGp8nfH