Maps in Go
Key-Value Collections for Efficient Data Access
What is a Go Map?
A map is a built-in data structure that associates values with unique keys. It provides fast lookups, additions, and deletions.
Declaration & Initialization
Maps can be created using the make function or a map literal:
scores := make(map[string]int) capitals := map[string]string{"Japan": "Tokyo", "France": "Paris"}
Key Characteristics
- Unordered collection
- Fast lookups (O(1) average time complexity)
- Keys must be comparable (cannot use slices, maps, or functions as keys)
- Maps are reference types (passing a map to a function passes a reference)
Common Operations
Add or update: m["key"] = value
Retrieve: value = m["key"]
Delete: delete(m, "key")
Check existence: value, exists := m["key"]
Concurrency Note
Maps in Go are not safe for concurrent use. When multiple goroutines access a map, you must use synchronization mechanisms like sync.Mutex
.