Sobes.tech
Junior — Middle

Is it possible to use a data structure as a key in a map or hash table?

sobes.tech AI

Answer from AI

In Go, a data structure can be used as a key in a map if it satisfies the comparability requirement (comparable). This means that all fields of the structure must be of types that can be compared using the == operator.

For example, structures containing only basic types (int, string, bool, etc.) or other comparable structures can be keys. However, structures containing slices, maps, or functions cannot be keys, as these types are incomparable.

Example:

package main

import "fmt"

type Point struct {
    X, Y int
}

func main() {
    m := make(map[Point]string)
    p := Point{X: 1, Y: 2}
    m[p] = "point"
    fmt.Println(m[p]) // output: point
}

If the structure contains incomparable fields, the compiler will produce an error when attempting to use it as a map key.