Decision patterns, reasoning and tradeoffs for idiomatic Go software design
Both `sync.Map` and `map` with `sync.Mutex` are concurrency-safe options in Go. The choice depends on runtime access patterns and operational requirements.
// Using sync.Map import "sync" var registry sync.Map func register(key string, value any) { registry.Store(key, value) } func get(key string) (any, bool) { return registry.Load(key) }
// Using map + sync.Mutex import "sync" var ( mu sync.Mutex registry = make(map[string]any) ) func register(key string, value any) { mu.Lock() defer mu.Unlock() registry[key] = value } func get(key string) (any, bool) { mu.Lock() defer mu.Unlock() val, ok := registry[key] return val, ok }
Use sync.Map when:
Use map with sync.Mutex when:
Both approaches are valid and safe. Choose based on expected load, not based on subjective stylistic preferences.