Introduction
A map in Go is a built-in reference type that associates keys with values, implemented internally as a hash table. Maps provide fast average-case lookup, insertion, and deletion. Keys must be a comparable type (such as strings, numbers, or structs made only of comparable fields), while values can be of any type, including other maps or slices. Because Go does not guarantee any particular iteration order for maps, code that depends on a stable order must sort the keys explicitly.
Cricket analogy: Like a scorecard keyed by player name looking up runs instantly, Virat Kohli's total pops up in O(1) average time, but flipping through the scorecard doesn't guarantee the batting order.
Syntax
// Declaration with make
ages := make(map[string]int)
// Map literal
capitals := map[string]string{
"France": "Paris",
"Japan": "Tokyo",
}
// Comma-ok idiom for existence checks
value, ok := ages["Alice"]
// Deleting a key
delete(capitals, "Japan")Explanation
make(map[string]int) creates an empty, ready-to-use map. A map literal like capitals initializes keys and values directly. The comma-ok idiom value, ok := ages["Alice"] returns the zero value and false for ok when the key is absent, letting you distinguish a genuinely stored zero value from a missing key. The zero value of a map type is nil; reading from a nil map behaves like reading from an empty map and is safe, but writing to a nil map causes a runtime panic, so nil maps must be initialized with make or a literal before being written to. delete(m, key) removes a key and is a no-op if the key doesn't exist.
Cricket analogy: Like initializing a fresh scorebook with make() before a match, checking runs, ok := scores["Dhoni"] tells you whether he actually batted for zero runs or never played, and an uninitialized scorebook can be read but not written to.
Example
package main
import "fmt"
func main() {
inventory := map[string]int{
"apples": 10,
"bananas": 5,
}
inventory["cherries"] = 20
if count, ok := inventory["bananas"]; ok {
fmt.Println("bananas in stock:", count)
}
if _, ok := inventory["grapes"]; !ok {
fmt.Println("grapes not tracked")
}
delete(inventory, "apples")
fmt.Println("map size after delete:", len(inventory))
}Output
bananas in stock: 5
grapes not tracked
map size after delete: 2Key Takeaways
- Maps store key-value pairs and require comparable key types.
- The comma-ok idiom distinguishes a stored zero value from a missing key.
- Reading from a nil map is safe; writing to one panics.
- Map iteration order is never guaranteed by the language spec.
- delete(m, key) removes an entry and is safe even if the key is absent.
Practice what you learned
1. What happens when you write to a nil map?
2. What is the purpose of the comma-ok idiom `v, ok := m["key"]`?
3. What is guaranteed about the order of a `for k, v := range m` loop over a Go map?
4. What types are valid as map keys in Go?
5. What does delete(inventory, "apples") do if "apples" is not a key in inventory?
Was this page helpful?
You May Also Like
Slices in Go
A dynamically-sized, flexible view into an underlying array, the go-to collection type in idiomatic Go.
Structs in Go
A composite type that groups related fields together, forming the basis for custom data modeling in Go.
for Loops in Go
Master Go's single looping construct, which covers classic for, while-style, infinite, and range-based loops.
The sync Package in Go
The sync package provides primitives like WaitGroup, Mutex, and Once for coordinating goroutines and protecting shared state.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics