On Tue, Nov 10, 2020 at 7:09 PM 'Kilos' via golang-nuts <
golang-nuts@googlegroups.com> wrote:

> Thanks for reply, but I want to know the underlying reason about it, I
> think the reason is in how the runtime functions works.
> And I'm sorry about the empty picture, when I write this, I just copy the
> screenshot in this, the code is https://play.golang.org/p/fSPpo4_-k57
>

Think about what it means to mutate a map while iterating over it. Do you
want the `range` operator to enumerate all the key:value pairs before
returning the first result? That's incredibly expensive. Also, what happens
if instead of inserting a new key you delete a key that is about to be
enumerated? Consider what happens whether or not the `range` operator
enumerates all keys before returning the first result.

Dan's reply regarding the map's hash seed being randomized to thwart
security attacks that rely on a predictable map hash function is the
proximate cause of the behavior you're seeing. But even without that
security mechanism you would still experience unpredictable behavior when
mutating a map while iterating over it. It's just that the problem would
depend only on the specific values (i.e., keys) used in your example code.

Do not mutate a map while iterating over it unless you're using something
like a functional programming language that provides guarantees about the
behavior in that case. Go documents the behavior here:
https://golang.org/ref/spec#RangeClause. Specifically,


   1. n/a
   2. n/a
   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.
   4. n/a



-- 
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CABx2%3DD-Mmug3_%3D38Z7osPEf%2B8U%2BMHVXdCeydB%3D61wQztHk7_3w%40mail.gmail.com.

Reply via email to