Sobes.tech
Junior

What property should a key have in a Map data structure?

sobes.tech AI

Answer from AI

The key in a Go map data structure must be comparable.

Typical comparable types in Go:

  • Boolean (bool)
  • Numeric types (int, float64, complex128, etc.)
  • Strings (string)
  • Pointers (*T)
  • Channels (chan T)
  • Interfaces (interface{}) (if the value inside is comparable)
  • Structs (struct) (if all fields are comparable)
  • Arrays (array) (if element type is comparable)

Examples of non-comparable types:

  • Slices (slice)
  • Some interfaces containing non-comparable types
  • Functions (func)
  • Maps (map)

Example of using a comparable type (string) as a key:

// Creating a map with string keys and int values
m := make(map[string]int)

// Adding elements
m["apple"] = 1
m["banana"] = 2

// Accessing an element
value := m["apple"] // value == 1

Example of attempting to use a non-comparable type (slice) as a key (will cause a compile-time error):

/*
// Compile error: invalid map key type []int
m := make(map[[]int]string)
*/