0

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 {
}
2
  • Because you are taking the address of struct it is providing with last value at address pointing to struct A Commented May 17, 2018 at 6:23
  • Do not think (here guess): Always consult the spec. Commented May 17, 2018 at 7:29

2 Answers 2

7

The language spec says:

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

Sign up to request clarification or add additional context in comments.

Comments

2
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.