How to Use Maps in Go – Best Practices for Key-Value Data
What is a Map?
A map is Go's built-in hash table type, storing unordered key-value pairs.
Declaring and Using Maps
ages := map[string]int{
"Alice": 25,
"Bob": 30,
}
ages["Charlie"] = 35 // add a new key
fmt.Println(ages["Alice"]) // 25
value, exists := ages["Dave"]
if !exists {
fmt.Println("Dave not found")
}
delete(ages, "Bob")
Best Practices
- Always check for existence using the two-value form (
value, ok := map[key]) to distinguish a missing key from a zero value. - Maps in Go are unordered — never rely on iteration order when looping with
for key, value := range map. - Use
make(map[string]int)to initialize an empty map before adding keys, to avoid a nil map panic on write.
PreviousGo Arrays vs Slices – Key Differences and Performance Tips
Next Structs and Methods in Go – Composition over Inheritance
Ready to master real-world Go skills?
Learn Go hands-on with mentor-led, live sessions.
.png)