Nondeterministic Behavior of for Loop Ranging Over a map

109 views
Skip to first unread message

Kaveh Shahbazian

unread,
May 26, 2020, 1:33:31 AM5/26/20
to golang-nuts
Why the output of this code is nondeterministic?


package main

import (
   
"fmt"
)

func main
() {
    series
:= make(map[int]int)

    series
[0] = 0

    i
:= 1
   
for k, v := range series {
        fmt
.Println(k, v)
       
if i < 10 {
            series
[i] = i
       
}
        i
++
   
}
}

(There is no implication in this question, regarding how maps, or for loops ranging over them, should behave. I'm just trying to understand)

Paul Jolly

unread,
May 26, 2020, 1:37:34 AM5/26/20
to Kaveh Shahbazian, golang-nuts
> Why the output of this code is nondeterministic?

See https://golang.org/ref/spec#For_statements, specifically the "For
statements with range clause" subheading, specifically this bullet:

> 3. The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced. If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is nil, the number of iterations is 0.

Kaveh Shahbazian

unread,
May 26, 2020, 1:39:41 AM5/26/20
to golang-nuts
Thank you Paul,

Jesse McNelis

unread,
May 26, 2020, 2:27:11 AM5/26/20
to Paul Jolly, Kaveh Shahbazian, golang-nuts
The implementation actually intentionally makes the iteration order more varied to avoid people relying on any particular ordering. So much so that some people started relying on the order to be random....

Message has been deleted

Dan Kortschak

unread,
May 26, 2020, 3:09:44 AM5/26/20
to golang-nuts
Also to prevent algorithmic complexity attacks like this
http://ocert.org/advisories/ocert-2011-003.html


Kaveh Shahbazian

unread,
May 26, 2020, 9:00:09 AM5/26/20
to golang-nuts
Thank you, I didn't know about this attack (of-course I need to spend some time to understand it).
Reply all
Reply to author
Forward
0 new messages