Sobes.tech
Junior — Middle

Kas struktuureid saab kasutada võtmetena assotsiatiivses massiivis või kaardil?

sobes.tech AI

Vastus AI-lt

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 the 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.