A pedantic question about updating a map during iteration

75 views
Skip to first unread message

Kevin Chowski

unread,
Aug 2, 2022, 11:20:24 PM8/2/22
to golang-nuts
Hello Go gurus,

I think there is some ambiguity in the language spec about what happens when a map entry is updated during iteration. Quoting the spec (https://go.dev/ref/spec#For_range):

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.

As per my read of the spec, there is no guarantee about what happens when you update a map key in-place.

For example, is this program guaranteed to print "1 1"? https://go.dev/play/p/PeBEXKp1deH

Apologies if I just missed some other part of the spec that ensures this.

Thanks in advance for your time,
Kevin

burak serdar

unread,
Aug 2, 2022, 11:34:59 PM8/2/22
to Kevin Chowski, golang-nuts
None of the conditions specified in that clause applies for updating key in-place. The way I read it, a new entry is not added, so the iteration should visit every entry only once. Thus, the program always prints "1 1".

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/c4f1d37c-84bb-49c9-a935-7b1f560688e4n%40googlegroups.com.

Jan Mercl

unread,
Aug 3, 2022, 2:32:34 AM8/3/22
to Kevin Chowski, golang-nuts
> For example, is this program guaranteed to print "1 1"? https://go.dev/play/p/PeBEXKp1deH

Yes, because the range iteration loop does not add/delete any items.
Reply all
Reply to author
Forward
0 new messages