Sobes.tech
Junior — Middle

Millised andmetüübid on lubatud võtmetena kaardistruktuuris?

sobes.tech AI

Vastus AI-lt

In Go, map keys can only be of data types that support the comparison operation (comparable). This means that keys can be:

  • Boolean values (bool)
  • Numbers (int, float, complex, etc.)
  • Strings (string)
  • Pointers
  • Interfaces, if the dynamic type supports comparison
  • Structures, if all their fields are comparable

Slices, maps, functions, and other non-comparable types cannot be used as keys because they do not support the == operator.

Example:

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

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

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