Sobes.tech
Junior — Middle

Can the order of traversal of elements in a Map data structure be guaranteed?

sobes.tech AI

Answer from AI

In Go, the order of iteration over elements in a map data structure is not guaranteed and is random. This is intentionally done to prevent code from depending on the iteration order and to enhance security.

If a guaranteed order is needed, usually:

  • Extract keys into a slice
  • Sort the slice
  • Iterate over the map using 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])
}

Thus, you cannot rely on the iteration order of a map in Go.

Can the order of traversal of elements in a Map data… - sobes.tech