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

spec: IncDec on empty Map creates an entry - undefined behavior? #35981

Closed
JeremyLoy opened this issue Dec 5, 2019 · 3 comments
Closed

spec: IncDec on empty Map creates an entry - undefined behavior? #35981

JeremyLoy opened this issue Dec 5, 2019 · 3 comments

Comments

@JeremyLoy
Copy link

What version of Go are you using (go version)?

13.3

Does this issue reproduce with the latest release?

Yes, verified in playground

What operating system and processor architecture are you using (go env)?

Darwin amd64

What did you do?

I used the IntDec Statement (++) on an empty, non-nil map.

https://play.golang.org/p/BGhREs68GiW

What did you expect to see?

Not sure! I wasn't able to find this behavior in the spec

The closest I could find is this paragraph for IntDec Statements which states that it is possible to use IntDec on maps, but it makes no mention of the behavior if the key/value pair doesn't exist.

What did you see instead?

An entry in the map was created with the value of 1

@bradfitz
Copy link
Contributor

bradfitz commented Dec 5, 2019

The spec says:

if the map is nil or does not contain such an entry, a[x] is the zero value for the element type of M

and:

The "++" and "--" statements increment or decrement their operands by the untyped constant 1.

And:

The following assignment statements are semantically equivalent:
x++ .... x += 1

And:

An assignment operation x op= y where op is a binary arithmetic operator is equivalent to x = x op (y) but evaluates x only once.

Therefore,

m["go"]++

is equivalent to:

m["go"] = m["go"] + 1

And because m["missing key"] means the zero value, that means:

m["go"] = 0 + 1

I think this is fully specified.

@bradfitz bradfitz changed the title IncDec on empty Map creates an entry - undefined behavior spec: IncDec on empty Map creates an entry - undefined behavior Dec 5, 2019
@bradfitz bradfitz changed the title spec: IncDec on empty Map creates an entry - undefined behavior spec: IncDec on empty Map creates an entry - undefined behavior? Dec 5, 2019
@randall77
Copy link
Contributor

I concur, this is not a bug.

@JeremyLoy
Copy link
Author

Interesting. My mistake. Sorry for wasting your time

@golang golang locked and limited conversation to collaborators Dec 4, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants