Go函数写入同一张地图

I am trying to familiarize with go routines. I have written the following simple program to store the squares of numbers from 1-10 in a map.

func main() {
    squares := make(map[int]int)
    var wg sync.WaitGroup
    for i := 1; i <= 10; i++ {
        go func(n int, s map[int]int) {
            s[n] = n * n
        }(i, squares)
    }
    wg.Wait()
    fmt.Println("Squares::: ", squares)
}

At the end, it prints an empty map. But in go, maps are passed by references. Why is it printing an empty map?

As pointed out in the comments, you need to synchronize access to the map and your usage of sync.WaitGroup is incorrect.

Try this instead:

func main() {
    squares := make(map[int]int)
    var lock sync.Mutex
    var wg sync.WaitGroup
    for i := 1; i <= 10; i++ {
        wg.Add(1) // Increment the wait group count
        go func(n int, s map[int]int) {
            lock.Lock() // Lock the map
            s[n] = n * n
            lock.Unlock()
            wg.Done() // Decrement the wait group count
        }(i, squares)
    }
    wg.Wait()
    fmt.Println("Squares::: ", squares)
}

sync.Map is what you are actually looking for, modified the code to suit your usecase here,

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

P.S. Had to add some sleep so that the program does not finish before all the go routines are called.