Junior — Middle
Is it possible to perform safe data reading from a map data structure without the risk of errors?
sobes.tech AI
Answer from AI
In Go, reading from a map is safe if no one is modifying the map at the same time. However, if there is concurrent writing (adding, deleting, or modifying elements), reading can lead to a panic (runtime error).
To safely read from a map in a multithreaded environment, the following are usually used:
- sync.RWMutex — to lock the map for writing and allow concurrent reads
- sync.Map — a specialized thread-safe data structure for maps
Example with RWMutex:
var (
m = make(map[string]int)
mu sync.RWMutex
)
func read(key string) (int, bool) {
mu.RLock()
defer mu.RUnlock()
val, ok := m[key]
return val, ok
}
func write(key string, val int) {
mu.Lock()
defer mu.Unlock()
m[key] = val
}
Thus, safe reading is possible if synchronization with writing is ensured.