Junior
What data types can be used as keys in a map in Go?
sobes.tech AI
Answer from AI
Keys in a Go map can be types for which the equality operation == is defined. These include:
- Numeric types:
int,int8,int16,int32,int64,uint,uint8,uint16,uintptr,float32,float64,complex64,complex128. - Boolean type:
bool. - String type:
string. - User-defined types based on the above (e.g.,
type MyInt int). - Pointers:
*T(for any typeT). - Channels:
chan T(for any typeT). - Interfaces:
interface{}or a named interface, if its dynamic type satisfies the comparability condition. - Structs:
struct, if all fields are comparable. - Arrays:
[n]T, if the element typeTis comparable.
Types that cannot be used as map keys:
- Slices (
slice). - Functions (
func). - Maps (
map).
The reason is that these types do not have a defined == operation. Slices, functions, and maps are not comparable.
Example usage:
// Valid keys
var m1 map[int]string
var m2 map[string]int
var m3 map[*byte]bool
var m4 map[struct{X, Y int}]float64 // Fields are comparable
// Invalid keys
// var m5 map[]int // Slice
// var m6 map[func()]int // Function
// var m7 map[map[int]string]int // Map