Go: what determines the iteration order for map keys?

后端 未结 4 583
[愿得一人]
[愿得一人] 2021-01-17 15:27

The Go Programming Language Specification says:

3. The iteration order over maps is not specified. [...]

That\'s to be expected

4条回答
  •  一生所求
    2021-01-17 15:57

    To extend @user811773 answer. A semi-random range clause iteration does not mean that the chance of returning each element in a map is also equal. See https://medium.com/i0exception/map-iteration-in-go-275abb76f721 and https://play.golang.org/p/GpSd8i7XZoG.

    package main
    
    import "fmt"
    
    type intSet map[int]struct{}
    
    func (s intSet) put(v int) { s[v] = struct{}{} }
    func (s intSet) get() (int, bool) {
        for k := range s {
            return k, true
        }
        return 0, false
    }
    func main() {
        s := make(intSet)
        for i := 0; i < 4; i++ {
            s.put(i)
        }
        counts := make(map[int]int)
        for i := 0; i < 1024*1024; i++ {
            v, ok := s.get()
            if !ok {return}
            counts[v]++
        }
        for k, v := range counts {
            fmt.Printf("Value: %v, Count: %v\n", k, v)
        }
    }
    /*
    Value: 1, Count: 130752
    Value: 2, Count: 130833
    Value: 0, Count: 655840
    Value: 3, Count: 131151
    */
    

提交回复
热议问题