为什么地图上没有按键

I created a map:

l := make(map[*A]string)

where A is:

type A struct{}

Then added key-values into it:

a1 := &A{}
a2 := &A{}
a3 := &A{}

l[a1] = "a1"
l[a2] = "a2"
l[a3] = "a3"

I expected to see all values ("a1", "a2", "a3") while doing range

for k, v := range l{
    fmt.Println(k, v)
}

But I see only the last one.

Why that happens? https://play.golang.org/p/GSdUWzExxLK

Because your struct has no fields, Go optimizes away all pointers to it to the same address, so you're using the same key every time. Give the struct a field (even if you never put a value in it) and you'll get your expected behavior.

Playground: https://play.golang.org/p/n-WUZ9wqpGJ

You can read more about empty structs (including this pointer behavior) on Dave Cheney's blog.

It's mentioned only briefly in the spec, under Sizes and Alignments, and is in fact the very last sentence in the spec:

A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. Two distinct zero-size variables may have the same address in memory.

This is because A is an empty structure. As it cannot change go always assigns it the same memory address. If you add a field to A it will start working:

type A struct{a string}

func main() {
    a1 := A{}
    a2 := A{}

    l := make(map[*A]string)
    l[&a1] = "a1"
    l[&a2] = "a2"

    for i, v := range l{
        i := i
        fmt.Println(&i, v)
    }
}

Prints:

0x40e138 a1
0x40e150 a2

https://play.golang.org/p/hYzU73kbVPV

Dave Cheney goes into more depth here:

https://dave.cheney.net/2014/03/25/the-empty-struct