Suppose we add a value to a map using a pointer as the key. Could the memory address of this pointer ever change? If so, will looking it up in the map fail because when it was inserted, it had a different memory address?
Asked
Active
Viewed 7,792 times
1 Answers
12
Could the memory address change, in the pointers-as-uints sense? Yes, but outside of the unsafe package go doesn't expose pointers as uints. So, will looking it up in the map fail? No.
See more at the spec. The linked section even includes a pointer-keyed map as an example.

W. Cybriwsky
- 511
- 3
- 6
-
6Same idea from another angle: the spec's promised to keep pointer-keyed maps working if any future implementation has a moving GC. – twotwotwo Jan 04 '16 at 07:05
-
@twotwotwo Where? I can't see that promise in the spec – Nearoo Jan 08 '22 at 15:22
-
Yeah, that's a fair criticism of my phrasing. The idea is that if things like pointer comparisons or pointer-keyed maps are valid according to the spec, the usual ideas of how equality and maps work should continue to apply as the implementation changes--pointers that were equal shouldn't start comparing unequal due to GC, and a key that once found an entry in a map shouldn't suddenly fail to due to GC. But I'm not saying there's a specific, explicit sentence in the spec about pointer-keyed maps working in a hypothetical Go implementation with a moving GC. – twotwotwo Jan 26 '22 at 17:27