Sobes.tech
Senior

What is the order of traversal of elements in a map in Go? (fixed by a certain algorithm / arbitrary, determined at compile time / arbitrary, determined at runtime)

sobes.tech AI

Answer from AI

In Go, the order of iteration over elements in a map is random and determined at runtime. This means that with each iteration over a map, the order of keys may differ, and it is not fixed by any algorithm.

This is intentionally done to prevent code from depending on the iteration order and to enhance security (for example, to make attacks based on predictable order more difficult).

Example:

package main

import "fmt"

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

The output order may vary each time you run the program.