Senior
How does map differ from sync.Map?
sobes.tech AI
Answer from AI
map in Go is a built-in data type for storing key-value pairs, but it is not thread-safe. Concurrent access from multiple goroutines without synchronization can lead to data races and panics.
sync.Map is a specialized structure from the sync package that provides thread-safe access to data without the need for external locking.
Main differences:
- Thread safety:
maprequires external synchronization (e.g., usingsync.Mutex),sync.Mapis built-in. - API:
sync.Maphas methodsLoad,Store,LoadOrStore,Delete,Range, whereas a regularmapuses bracket notation. - Performance:
sync.Mapis optimized for scenarios with frequent reads and infrequent writes. For intensive writes, a regularmapwith a mutex might be faster.
Example of using sync.Map:
var m sync.Map
// Store
m.Store("key", "value")
// Load
if val, ok := m.Load("key"); ok {
fmt.Println(val)
}
// Delete
m.Delete("key")
// Iterate
m.Range(func(k, v interface{}) bool {
fmt.Println(k, v)
return true
})
Choose a map with a mutex if you have complex logic and many writes, and sync.Map if you need to quickly and simply ensure thread safety for predominantly read data.