Sobes.tech
Junior — Middle

What types of data can serve as a key in a map container?

sobes.tech AI

Answer from AI

In Go, the key in a map can only be of types that are comparable. This means that the key type must have the == operator defined.

Suitable key types:

  • Boolean values (bool)
  • Numbers (int, float64, uint8, etc.)
  • Strings (string)
  • Pointers
  • Channels
  • Interfaces, if the dynamic type is comparable
  • Structs, if all their fields are comparable

Cannot be used as keys:

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

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"

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

What types of data can serve as a key in a map… - sobes.tech