Go结构体指针不唯一

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

Go struct pointers not unique

问题

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

package main

import (
	"fmt"
)

type Thingy struct{}

var things map[*Thingy]int

func main() {
	things = make(map[*Thingy]int)

	thing1 := new(Thingy)
	tracePointer("thing1", thing1)
	things[thing1] = 1

	thing2 := new(Thingy)
	tracePointer("thing2", thing2)
	things[thing2] = 2

	thing3 := &Thingy{}
	tracePointer("thing3", thing3)
	things[thing3] = 3

	fmt.Printf("Amount of things: %d\n", len(things))
}

func tracePointer(identifier string, obj interface{}) {
	fmt.Printf("%s pointer: %p\n", identifier, obj)
}

输出:

thing1 pointer: 0x546570
thing2 pointer: 0x546570
thing3 pointer: 0x546570
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.

package main

import (
	"fmt"
)

type Thingy struct{}

var things map[*Thingy]int

func main() {
	things = make(map[*Thingy]int)

	thing1 := new(Thingy)
	tracePointer("thing1", thing1)
	things[thing1] = 1

	thing2 := new(Thingy)
	tracePointer("thing2", thing2)
	things[thing2] = 2

	thing3 := &Thingy{}
	tracePointer("thing3", thing3)
	things[thing3] = 3

	fmt.Printf("Amount of things: %d\n", len(things))
}

func tracePointer(identifier string, obj interface{}) {
	fmt.Printf("%s pointer: %p\n", identifier, obj)
}

Ouput:

thing1 pointer: 0x546570
thing2 pointer: 0x546570
thing3 pointer: 0x546570
Amount of things: 1

答案1

得分: 2

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

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

thing1指针: 0x10328000
thing2指针: 0x10328020
thing3指针: 0x10328021
物品数量: 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.

thing1 pointer: 0x10328000
thing2 pointer: 0x10328020
thing3 pointer: 0x10328021
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:

确定