Junior — Middle
Kas on võimalik garantida Map andmestruktuuri elementide läbimise järjekord?
sobes.tech AI
Vastus AI-lt
In Go, the order of traversal of elements in the data structure map is not guaranteed and is random. This is intentionally done to prevent code from depending on the traversal order and to enhance security.
If a guaranteed order is needed, usually:
- Keys are extracted into a slice
- The slice is sorted
- The map is traversed according to the sorted keys
Example:
keys := make([]string, 0, len(myMap))
for k := range myMap {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, myMap[k])
}
This way, you cannot rely on the traversal order of map in Go.