英文:
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
//编辑
正如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
//edit
As James Henstridge pointed out in the comments, struct{}
's address changes if they are inside a bigger struct.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论