Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading