Sobes.tech
Junior — Middle

What data types are suitable for use as keys in a Map data structure?

sobes.tech AI

Answer from AI

In Go, only data types that support the comparison operation (==) can be used as keys for a map. This means that keys can be:

  • Boolean values (bool)
  • All kinds of numbers (int, float64, uint8, etc.)
  • Strings (string)
  • Pointers
  • Channels
  • Interfaces, if the concrete values inside them are comparable
  • Structs and arrays, if all their fields or elements are comparable

Slices, maps, and functions cannot be used as keys because they do not support comparison.

Example:

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

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

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

If you need to use incomparable types, such as slices, as keys, you typically apply hashing or convert them to a string.

What data types are suitable for use as keys in a Map… - sobes.tech