For Kurtis: Thank you, I will remember this: You cannot safely mutate a Go map while iterating over it with the `range` operator.
I will not do this when programming, but when I learned about this, then I want to know the underlying reason. And now, I have known. 在2020年11月11日星期三 UTC+8 下午12:23:38<Kurtis Rader> 写道: > On Tue, Nov 10, 2020 at 8:12 PM 'Kilos' via golang-nuts < > [email protected]> wrote: > >> For Kurtis: >> I know the map will choose random hash seed to init itself, and the >> iterator will also choose random order to iterate map. >> And I know it is a bad idea to add or delete a key when iterating a map, >> but I want to know what causes the inpredictable result, not the key's >> iterating order, but the key's count that was printed. >> > > The count is wrong, sometimes, because you are relying on undefined > behavior. Ignore the Go map implementation as it is irrelevant to your > question. If Go's map implementation used something like a binary tree > without mutating the keys (to make it hard to create a DOS attack) your > example program would still behave unpredictably if you vary the keys. > Repeat after me: You cannot safely mutate a Go map while iterating over it > with the `range` operator. This is true for most map data structures in > most, non-functional (e.g., Haskell), programming languages. > > -- > 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 [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/fda81dd0-59a6-407d-812a-2903584b0e3fn%40googlegroups.com.
