Sobes.tech
Junior — Middle

Is it possible to use a non-empty structure as a key in a Map container?

sobes.tech AI

Answer from AI

In Go, any type that supports comparison with the == operator can be used as a key in a map. Structs can be used as keys if all their fields are comparable. A non-empty struct is suitable if it does not contain slices, maps, functions, or other non-comparable types.

Example of using a struct as a key:

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 struct contains non-comparable fields, such as slices, it cannot be used as a key.

Is it possible to use a non-empty structure as a key… - sobes.tech