Sobes.tech
Senior

Is the standard map in Go concurrency-safe? What alternatives exist?

sobes.tech AI

Answer from AI

A standard map in Go is not thread-safe. If multiple goroutines read and write to the same map simultaneously without synchronization, it will cause a runtime panic.

To work safely with maps in a concurrent environment, you can use the following alternatives:

  • sync.Map — a specialized structure from the sync package, optimized for concurrent access. It provides methods Load, Store, Delete, and Range, suitable for scenarios with frequent reads and infrequent writes.

  • Mutexes (sync.Mutex or sync.RWMutex) — wrap access to a regular map with locks to ensure exclusive access during writes and safe access during reads.

Example of using sync.Map:

var m sync.Map

// Write
m.Store("key", "value")

// Read
if val, ok := m.Load("key"); ok {
    fmt.Println(val)
}

// Delete
m.Delete("key")

If more complex logic or high performance is needed, you can use third-party libraries that implement thread-safe data structures.