英文:
Is it safe to use pointers as map keys in Go?
问题
假设我们使用指针作为键将一个值添加到映射中。这个指针的内存地址会发生变化吗?如果会变化,那么在查找映射时会失败吗?因为在插入时,它的内存地址是不同的。
英文:
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?
答案1
得分: 12
内存地址在指针作为无符号整数的意义上是否会改变?是的,但是在Go语言中,除了unsafe包之外,不会将指针公开为无符号整数。那么,在映射中查找会失败吗?不会。
请参阅规范。链接的部分甚至包括了以指针为键的映射作为示例。
英文:
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.
1: https://golang.org/pkg/unsafe/ "the unsafe package"
2: https://golang.org/ref/spec#Map_types "the spec for map types"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论