我正在尝试创建元素映射。我想使用指针而不是整数作为键。问题是......我一直得到相同的指针。不管我创造了多少次。为什么是这样?如果可能的话,如何在不使用 unsafe 包的情况下获得真正的指针。
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
相关分类