Sobes.tech
Junior — Middle

Why is the order of elements not guaranteed and appears random in map?

sobes.tech AI

Answer from AI

In Go, the built-in map structure is implemented using a hash table, and the order of traversal of elements is not guaranteed and can change between iterations. This is because:

  • The hash function distributes keys across buckets, and the order of buckets is not fixed.
  • For security and to prevent dependence on order, starting from Go 1.0, the traversal order of maps is deliberately randomized on each iteration.

Therefore, when traversing a map, the order of elements appears random and should not be relied upon in program logic. If a sorted output is needed, 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.

Why is the order of elements not guaranteed and… - sobes.tech