Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 987
Edgar Avatar asked Jan 25 '26 14:01

Edgar


1 Answers

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

like image 193
colm.anseo Avatar answered Jan 28 '26 09:01

colm.anseo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!