How to Use Goroutine-Safe Data Structures

Use sync.Mutex to wrap standard types or sync.Map for concurrent access in Go, as no built-in goroutine-safe collections exist.

Go does not provide built-in goroutine-safe data structures; you must wrap standard types with synchronization primitives like sync.Mutex or use concurrent-safe types like sync.Map. For shared data accessed by multiple goroutines, protect the data with a mutex to prevent race conditions.

import "sync"

type SafeCounter struct {
    mu    sync.Mutex
    count int
}

func (c *SafeCounter) Inc() {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.count++
}

For read-heavy workloads with dynamic keys, use sync.Map which handles concurrency internally:

import "sync"

var m sync.Map

// Safe for concurrent use
m.Store("key", "value")
val, ok := m.Load("key")

For custom compressors or decompressors in archive/zip, ensure the function itself is safe to invoke from multiple goroutines, but remember each returned reader/writer is for single-goroutine use only.