Go Sync Map
In this tutorial, you'll learn about Go sync.Map vs Mutex Map. We cover key concepts, practical examples, and best practices.
sync.Map -- Use sync.Map for specific patterns: write-once/read-many or disjoint keys across goroutines.
The Problem
sync.Map is not a drop-in replacement for map+Mutex. It's optimized for specific access patterns. For general use, sync.RWMutex + map is faster.
Wrong
var m sync.Map
m.Store("key", "value")
val, ok := m.Load("key")
m.Delete("key")
m.Range(func(k, v interface{}) bool {
fmt.Println(k, v)
return true
})
Output:
// sync.Map API different from regular map
Right
type Cache struct {
mu sync.RWMutex
m map[string]*Entry
}
func (c *Cache) Get(key string) *Entry {
c.mu.RLock()
defer c.mu.RUnlock()
return c.m[key]
}
Output:
// Simple, predictable performance
Prevention
- sync.Map for: write-once/read-many, or disjoint keys
- Regular map + RWMutex for general use
- sync.Map uses interface{} (no generics)
- sync.Map has LoadOrStore, LoadAndDelete
- Benchmark before choosing sync.Map
Common Mistakes with sync map
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro