Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: spec: clarify that map iteration always yields the latest version of an entry #70916

Open
prattmic opened this issue Dec 19, 2024 · 2 comments
Labels
Milestone

Comments

@prattmic
Copy link
Member

Proposal Details

Consider the following program (https://go.dev/play/p/wd1Ge2PIyAK):

package main

import "fmt"

func main() {
	m := map[string]string{
		"a": "original",
		"b": "original",
	}
	for k, v := range m {
		fmt.Println(k, v)
		m["a"] = "new"
	}
}

Map iteration order unspecified, so if "a" is produced first it will print:

a original
b original

If "b" is produced first, the spec does not specify whether this must print

b original
a new

Or if

b original
a original

is acceptable. In other words, is iteration required to produce the latest version of an entry, or is a stale version OK?

As far as I know, the gc map implementation has always produced the latest version of an entry. In fact, when implementing #54766 I fixed bugs I introduced that produced stale values under the assumption that the spec required it.

The spec does specify "If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced." In my opinion it would be odd to require deletion be tracked precisely, but not changes to values.

Thus I propose that the map portion of https://go.dev/ref/spec#For_range be amended to add "Iteration always produces the latest value of a map entry."

cc @griesemer @randall77

@gopherbot gopherbot added this to the Proposal milestone Dec 19, 2024
@ianlancetaylor ianlancetaylor moved this to Incoming in Proposals Dec 19, 2024
@zigo101
Copy link

zigo101 commented Dec 20, 2024

Same as/for slices?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Incoming
Development

No branches or pull requests

4 participants