Sobes.tech
Middle

What data types can be used as keys?

sobes.tech AI

Answer from AI

In Go, keys in a map can only be of types that support the comparison operation (==). This is because, to find a key in a hash table, keys need to be compared for equality.

Types that can be used as keys:

  • Primitive types: int, float64, string, bool, etc.
  • Pointers
  • Structs, if all their fields are comparable
  • Arrays, if elements are comparable

Types that cannot be used as keys:

  • Slices (slice)
  • Maps (map)
  • Functions

This is because these types do not support comparison using ==.

Example:

m := make(map[string]int)
m["key"] = 42

// Struct with comparable fields
 type Point struct {
     X, Y int
 }

m2 := make(map[Point]string)
m2[Point{1, 2}] = "A point"

Trying to use a slice or map as a key will result in a compile-time error.