在Go语言中,使用指针作为map的键是否安全?

huangapple go评论73阅读模式
英文:

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"

huangapple
  • 本文由 发表于 2016年1月4日 13:11:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/34585018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定