Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Go also randomizes the iteration of map keys, to emphasize that maps are unordered and code should not rely on insertion order. For demonstration:

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

  c
  a
  b
  a
  b
  c
Each run may produce different key orders.


I was under the assumption most languages to this.


Very few do, and only quite modern ones. Although I believe there are hashtable libraries where the iteration order is unspecified but generally consistent, only changing when a resize shuffles the elements into different buckets.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: