Sobes.tech
Junior — Middle

How to determine which value can be used as a key in a Map data structure?

sobes.tech AI

Answer from AI

In Go, a map key can be any type that supports comparison using the == operator. This means the key must be comparable.

What can be used as a key:

  • Primitive types: strings, numbers, boolean values.
  • Pointers.
  • Structs, if all their fields are comparable.

What cannot be used:

  • Slices, maps, functions, as they are not comparable.

Example:

m := make(map[string]int) // string is a valid key
m["key"] = 42

// Struct with comparable fields
type Point struct {
    X, Y int
}
var points = make(map[Point]string)
points[Point{1, 2}] = "A"

Trying to use a non-comparable type as a key will result in a compile-time error.