Go — Maps
Creating maps
package main
import "fmt"
func main() {
// Literal
ages := map[string]int{
"Alice": 30,
"Bob": 25,
}
// Make
m := make(map[string]int)
// Add entries
m["Charlie"] = 35
m["Diana"] = 28
fmt.Println(ages, m)
}
Map operations
ages := map[string]int{"Alice": 30, "Bob": 25}
// Access
fmt.Println(ages["Alice"]) // 30
// Check existence
age, ok := ages["Charlie"]
if ok {
fmt.Println("Charlie:", age)
} else {
fmt.Println("Charlie not found")
}
// Delete
delete(ages, "Bob")
// Length
fmt.Println("Size:", len(ages))
Iterating maps
ages := map[string]int{"Alice": 30, "Bob": 25, "Charlie": 35}
for name, age := range ages {
fmt.Printf("%s: %d\n", name, age)
}
Map as set
set := map[string]bool{}
set["Alice"] = true
set["Bob"] = true
// Check membership
if set["Alice"] {
fmt.Println("Alice is in the set")
}
Nested maps
users := map[string]map[string]interface{}{
"Alice": {
"age": 30,
"city": "NYC",
},
"Bob": {
"age": 25,
"city": "LA",
},
}
fmt.Println(users["Alice"]["city"])
Best practices
- Use
makefor large maps to pre-allocate - Always check the comma-ok idiom when accessing
- Maps are not safe for concurrent use — use
sync.Mapor mutexes - Use maps for lookup-heavy operations
Mini Practice
Write Go code that:
- Creates a map and iterates with
range - Uses the comma-ok idiom to check key existence
- Implements a word frequency counter
- Uses a map as a set
Up Next
In the next lesson, you'll learn about Structs — grouping related data.
Related Topics
Frequently Asked Questions about Maps
What is Maps in Go?
Maps is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Maps?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Maps.
Why is Maps important in Go?
Maps is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.