Skip to content

Go Sync Map

DodaTech 1 min read

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
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

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

**When is sync.Map faster?**

When keys are written once and read many times from different goroutines.

Does sync.Map support generics in Go 1.18+?

No. Use type assertions or custom wrapper.

Can I iterate sync.Map?

Yes, with Range(func(key, value interface{}) bool). Return false to stop.


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