Sobes.tech
Principal

What is the order of traversal of elements in a map container in Go?

sobes.tech AI

Answer from AI

In the Go language, the order of iteration over elements in a map container is not defined and is random. This is done intentionally to prevent code from depending on the iteration order and to enhance safety.

That is, during each iteration over a map, the order of keys may differ, and you cannot rely on the sequence of elements.

Example:

m := map[string]int{"a": 1, "b": 2, "c": 3}
for k, v := range m {
    fmt.Println(k, v)
}

On each run, the program may output keys in a different order.

If a ordered traversal is needed, you should extract the keys into a slice, sort it, and then iterate over the sorted keys.