How do I avoid 'concurrent map writes' errors in Go?

In Go, the "concurrent map writes" error occurs when multiple goroutines simultaneously write to a map without proper synchronization. To avoid this issue, we can use synchronization mechanisms such as mutexes or channels. Below is an example using a mutex to safely write to a map from multiple goroutines.

package main import ( "fmt" "sync" ) func main() { var mu sync.Mutex myMap := make(map[int]int) var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func(i int) { defer wg.Done() mu.Lock() myMap[i] = i * i // Safe write to the map mu.Unlock() }(i) } wg.Wait() fmt.Println(myMap) // Print the map after all goroutines finish }

concurrent map writes Go goroutines mutex synchronization