0

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
Tsiao Wang
  • 51
  • 7
  • 1
    BTW literally the first Google hit for "golang map iteration order" is https://stackoverflow.com/questions/9619479/go-what-determines-the-iteration-order-for-map-keys – Volker Sep 05 '22 at 12:54

1 Answers1

2

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.

Volker
  • 40,468
  • 7
  • 81
  • 87