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

Ok here is a correct clarification of what is happening when iterating over maps in Go. The author of this article doesn't seem to understand what is going on.

Ever since Go 1.0, they implemented a feature where when iterating over a map it will choose a random bucket, in the map, to start from and iterate from the start of each bucket to the end of the bucket in order and then move to the next bucket in order. The non-deterministic nature in this stems from the initial bucket to start from, which was chosen at random. This means that the number of different possible iterations of the same map is equal to the number of buckets in the map.

This leads to a problem with small maps (those less than 8 items). Because the max size of a bucket is 8 items, if a map has less than 8 items there will be only one ordering, and therefore for small maps (those with less than 8 items) the programmer could still rely on the iteration order of the map, which is not desired.

So along came this issue: https://code.google.com/p/go/issues/detail?id=6719 which seems to have a fix implemented in Go version 1.3. (Here is the revision log for the committed change: https://code.google.com/p/go/source/detail?r=6ea672cbfe43).

So as of Go version 1.3, the behaviour will be as follows. Buckets will be iterated over from bucket 1 to bucket N. But within each bucket iteration will start at a random index and then iterate through the bucket. For performance reasons, the random starting index for within each bucket will be determined at the start of iteration and will be the same for every bucket. Iteration over a map with 8 or fewer elements, a single bucket, will now be non-deterministic. It should be noted that this also means that the max number of possible different iterations of a map is 8, but that does not matter as it solves the problem of having programmers relying on iteration order no matter what size the map is (except for size 0 and 1).



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

Search: