Junior — Middle
Miks map kasutamisel ei ole elementide järjekord garanteeritud ja näib juhuslik?
sobes.tech AI
Vastus AI-lt
In Go, the built-in map structure is implemented using a hash table, and the order of traversing elements is not guaranteed and can change between iterations. This is because:
- The hash function distributes keys into buckets, and the order of buckets is not fixed.
- For security and to prevent dependency on order, from Go 1.0, the traversal order of the map is specifically randomized at each iteration.
Therefore, when traversing a map, the order of elements appears random and should not be used in program logic. If a sorted output is needed, the keys should be sorted separately:
m := map[string]int{"b": 2, "a": 1, "c": 3}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, m[k])
}
This way, you will get the elements in sorted order.