Skip to content

spec: can take the address of map[x] #11865

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

Closed
mei-rune opened this issue Jul 25, 2015 · 2 comments
Closed

spec: can take the address of map[x] #11865

mei-rune opened this issue Jul 25, 2015 · 2 comments

Comments

@mei-rune
Copy link

current golang cannot can take the address of map[x]. like this

 m := map[int]int{}
 v:= &m[1] // it will compile error

But sometimes this is useful while valueType is struct, like this:

 m := map[int]V{}
 v, ok := &m[1]
 // ok = true if exists.
 // ok = false if not exists
if ok {
  v.x += 1
  v.y += 1
  v.z += 1
} else {
  m[1] = V{x: 1, y: 1, z: 1}
}

This code is error for golang now, m type must is map[int]*V, the valueType must is a pointer. pointer will increased memory fragmentation and increasing GC

@dsnet
Copy link
Member

dsnet commented Jul 25, 2015

Hash tables typically grow automatically when the number of elements increases above a certain threshold. When it does, it reallocates a new underlying array and copies all of the old elements into the new one.

If you were able to take the address to an element, and then added an element to the map, causing a growth, what would the address be pointing at?

As you can see it would be very difficult to make pointers to map elements work.

See: https://groups.google.com/forum/#!topic/golang-nuts/V_5kwzwKJAY

@davecheney
Copy link
Contributor

You cannot take the address of a map value because map values are not addressable.

This restriction is in place because the map implementation may have to move values between hash map buckets, so callers must be prevented from taking the address of a map's value.

@mikioh mikioh changed the title can take the address of map[x] spec: can take the address of map[x] Jul 26, 2015
@golang golang locked and limited conversation to collaborators Aug 5, 2016
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