Middle
Milliseid andmetüüpe saab kasutada võtmetena?
sobes.tech AI
Vastus AI-lt
In Go, keys in a map can only be of types that support the comparison operation (==). This is because, to find a key in a hash table, the keys need to be compared for equality.
Types that can be used as keys:
- Primitive types:
int,float64,string,bool, etc. - Pointers
- Structs, if all their fields are comparable
- Arrays, if their elements are comparable
Types that cannot be used as keys:
- Slices (
slice) - Maps (
map) - Functions
This is because these types do not support comparison with ==.
Example:
m := make(map[string]int)
m["key"] = 42
// Struct with comparable fields
type Point struct {
X, Y int
}
m2 := make(map[Point]string)
m2[Point{1, 2}] = "A point"
Trying to use a slice or map as a key will result in a compile-time error.