{"id":2331,"date":"2020-06-20T22:37:06","date_gmt":"2020-06-20T17:07:06","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=2331"},"modified":"2020-06-20T22:37:19","modified_gmt":"2020-06-20T17:07:19","slug":"allowed-key-and-value-types-golang","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/allowed-key-and-value-types-golang\/","title":{"rendered":"Allowed key and value types for a map in Go (Golang)"},"content":{"rendered":"\n
Maps are golang builtin datatype similar to the hash table which maps a key to a value. . Below is the format for a map:<\/p>\n\n\n\n
map[key_type]value_type<\/code><\/pre>\n\n\n\nBoth key_type<\/strong> and value_type<\/strong> can be of different type or same type. For below example the key type is string<\/strong> and value type is int<\/strong><\/p>\n\n\n\nmap[string]int<\/code><\/pre>\n\n\n\nAllowed Key types in a Map<\/strong><\/p>\n\n\n\nThe map key can be any type that is comparable. Some of the comparable types as defined by go specification are<\/p>\n\n\n\n
- boolean<\/li>
- numeric<\/li>
- string,<\/li>
- pointer<\/li>
- channel<\/li>
- interface types<\/li>
- structs – if all it’s field type is comparable<\/li>
- array – if the type of value of array element is comparable<\/li><\/ul>\n\n\n\n
Some of the types which are not comparable as per go specification and which cannot be used as a key in a map are.<\/p>\n\n\n\n