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
", len(things))
}
func tracePointer(identifier string, obj interface{}) {
fmt.Printf("%s pointer: %p
", identifier, obj)
}
Ouput:
thing1 pointer: 0x546570
thing2 pointer: 0x546570
thing3 pointer: 0x546570
Amount of things: 1
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.