Sobes.tech
Junior — Middle

Can structures be used as keys in an associative array or map?

sobes.tech AI

Answer from AI

In Go, keys in a map can only be of types that support the comparison operation (operator ==). Structures can be used as keys if all their fields are comparable. For example, if a structure contains only basic types (int, string, etc.), it can be used as a key. However, if a structure contains slices, maps, or functions, it cannot be used as a key.

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.

Can structures be used as keys in an associative… - sobes.tech