gogo-map

What determines the order in which the results are generated from "for range" iteration of golang map?


I try to firgure out that what determines the order of results generated from "for range" iteration of golang map.

I found that it is neither determined by the order of keys nor by the order of pushing. which is really weired.

I want to figure this out. In terms of source code of golang, where can i find the implementation of "for range" map?

func main() {
    m := make(map[int]int)
    m[1] = 2
    m[2] = 3
    m[0] = 1
    m[4] = 5
    m[3] = 4

    for k, v := range m {
        fmt.Println(k, v)
    }
}
    // output
    // 1 2
    // 2 3
    // 0 1
    // 4 5
    // 3 4

Solution

  • I try to firgure out that what determines the order of results generated from "for range" iteration of golang map?

    Nothing, it's deliberately random/non-deterministic.

    You must not rely on iteration order.

    Source for map is https://go.googlesource.com/go/+/refs/heads/master/src/runtime/map.go But again: iteration is random, really. Nothing to see here.