Junior — Middle
Millised on piirangud ja omadused võtmete kasutamisel andmestruktuuris map?
sobes.tech AI
Vastus AI-lt
In Go, keys in a map must meet certain requirements:
-
The key must be comparable: This means that the key type must support the comparison operations
==and!=. For example, basic types (int, string, bool), pointers, structs, and arrays, if all their fields are comparable. -
Slices, maps, and functions cannot be used as keys: These types are not comparable and will cause a compile-time error.
-
Features:
- Structs can be keys if all their fields are comparable.
- If a struct contains a field of type slice or map, it cannot be a key.
-
Performance: Using large structs as keys can be inefficient due to copying.
Example:
m := make(map[string]int) // string is a valid key
// Invalid key:
// m2 := make(map[[]int]string) // compile error
// Struct with comparable fields:
type Point struct { X, Y int }
m3 := make(map[Point]string)
m3[Point{1,2}] = "A"
Therefore, when choosing a key, it is important to consider its comparability and immutability.