Key Types

While any type can be a value in a map, Go restricts which types can be used as keys.

Comparable Types

A type can be a map key if it is comparable using the == operator. This includes:

  • Boolean, Numeric, and String types.
  • Pointers and Channels.
  • Interface types.
  • Structs and Arrays (if they only contain comparable types).

Prohibited Types

The following types cannot be used as map keys because they are not comparable:

  • Slices
  • Maps
  • Functions

Struct Keys

Using a struct as a key is a powerful way to index data by multiple dimensions.

type Point struct {
    X, Y int
}

hits := make(map[Point]int)
hits[Point{1, 2}]++