MapsIntermediate
1Question 1 of 1
goHow do Maps work in Go and why are they not safe for concurrent writes?
Explanation & Concept
A Map in Go is a hash table reference type: `map[KeyType]ValueType`. Keys must be comparable types.
Go maps **are not safe for concurrent read and write operations**. Concurrent map access causes a fatal runtime crash. For concurrent environments, use `sync.RWMutex` or `sync.Map`.
Code Example
go
package main
import "fmt"
func main() {
scores := make(map[string]int)
scores["Alice"] = 95
// Safe read with comma-ok idiom
val, exists := scores["Bob"]
if !exists {
fmt.Println("Bob is not registered in the map!")
} else {
fmt.Println("Bob's score:", val)
}
}How It Works & Key Takeaways
The comma-ok idiom (`val, ok := map[key]`) safely distinguishes between a missing key and a key whose stored value happens to be zero.
Mock Test · 1 Questions · Optional
Ready for Package Management (Go Modules)?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions