Go结构体指针不唯一

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

Go struct pointers not unique

问题

我正在尝试创建一个元素的映射。我想使用指针而不是整数作为键。问题是...我一直得到相同的指针。无论我创建多少次,都是这样。为什么会这样?如果可能的话,我该如何获得一个真正的指针,而不使用不安全的包。

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Thingy struct{}
  6. var things map[*Thingy]int
  7. func main() {
  8. things = make(map[*Thingy]int)
  9. thing1 := new(Thingy)
  10. tracePointer("thing1", thing1)
  11. things[thing1] = 1
  12. thing2 := new(Thingy)
  13. tracePointer("thing2", thing2)
  14. things[thing2] = 2
  15. thing3 := &Thingy{}
  16. tracePointer("thing3", thing3)
  17. things[thing3] = 3
  18. fmt.Printf("Amount of things: %d\n", len(things))
  19. }
  20. func tracePointer(identifier string, obj interface{}) {
  21. fmt.Printf("%s pointer: %p\n", identifier, obj)
  22. }

输出:

  1. thing1 pointer: 0x546570
  2. thing2 pointer: 0x546570
  3. thing3 pointer: 0x546570
  4. Amount of things: 1
英文:

I'm trying to create a map of elements. I wanted to use a pointer rather then an integer as a key. The problem is... I keep getting the same pointer. No matter how many times I create it. Why is this? How do I get a real pointer, without using the unsafe package if possible.

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Thingy struct{}
  6. var things map[*Thingy]int
  7. func main() {
  8. things = make(map[*Thingy]int)
  9. thing1 := new(Thingy)
  10. tracePointer("thing1", thing1)
  11. things[thing1] = 1
  12. thing2 := new(Thingy)
  13. tracePointer("thing2", thing2)
  14. things[thing2] = 2
  15. thing3 := &Thingy{}
  16. tracePointer("thing3", thing3)
  17. things[thing3] = 3
  18. fmt.Printf("Amount of things: %d\n", len(things))
  19. }
  20. func tracePointer(identifier string, obj interface{}) {
  21. fmt.Printf("%s pointer: %p\n", identifier, obj)
  22. }

Ouput:

  1. thing1 pointer: 0x546570
  2. thing2 pointer: 0x546570
  3. thing3 pointer: 0x546570
  4. Amount of things: 1

答案1

得分: 2

struct{}是一个特殊情况,它始终使用0字节的内存,并且始终具有相同的地址。

如果你只想要一个虚拟指针,你可以使用type Thingy byte

  1. thing1指针: 0x10328000
  2. thing2指针: 0x10328020
  3. thing3指针: 0x10328021
  4. 物品数量: 3

<kbd>playground</kbd>

//编辑

正如James Henstridge在评论中指出的那样,如果struct{}位于更大的结构体内部,它的地址会发生变化。

http://play.golang.org/p/51_PhqDNhk

英文:

struct{} is a special case, it always uses 0 bytes of memory and will always have the same address.

If you just want a dummy pointer, you can use type Thingy byte.

  1. thing1 pointer: 0x10328000
  2. thing2 pointer: 0x10328020
  3. thing3 pointer: 0x10328021
  4. Amount of things: 3

<kbd>playground</kbd>

//edit

As James Henstridge pointed out in the comments, struct{}'s address changes if they are inside a bigger struct.

http://play.golang.org/p/51_PhqDNhk

huangapple
  • 本文由 发表于 2014年9月21日 07:26:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/25954237.html
匿名

发表评论

匿名网友

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

确定