o0omycomputero0o
o0omycomputero0o

Reputation: 3544

How golang map of struct as keytype work?

I don't know why Go given this following result. I think that a1 and a2 are two distinct pointers?

&{} !

Code

func main() {
    a1 := &A{}
    a2 := &A{}
    a3 := &A{}
    m2 := make(map[*A]string)
    m2[a1] = "hello"
    m2[a2] = "world"
    m2[a3] = "!"
    for k, v := range m2 {
        fmt.Println(k, v)
    }
}

type A struct {
}

Upvotes: 0

Views: 114

Answers (2)

Nathanael Mkaya
Nathanael Mkaya

Reputation: 121

func main() {
a1 := new(A)
a2 := new(A)//A{}
a3 := new(A)//A{}
m2 := make(map[**A]string)
m2[&a1] = "hello"
m2[&a2] = "world"
m2[&a3] = "!"
for k, v := range m2 {
    fmt.Println(k, v)
}
}

type A struct {
}

The above code kinda prints out what you need

Upvotes: 2

Art
Art

Reputation: 20402

The language spec says:

Pointers to distinct zero-size variables may or may not be equal.

Upvotes: 7

Related Questions