Go Tutorial · Data Structures · Lesson 14 of 30
Go Maps
Key-value maps: create, read, check existence, delete and iterate.
Creating and using maps
package main
import (
"fmt"
"strings"
)
func main() {
stock := map[string]int{"apples": 5, "pears": 2}
stock["plums"] = 12
stock["apples"] += 3
delete(stock, "pears")
fmt.Println(stock["apples"], len(stock))
counts := make(map[string]int)
for _, w := range strings.Fields("the cat and the hat") {
counts[w]++
}
fmt.Println(counts["the"], counts["dog"])
}
Output
8 2 2 0
Run this on your computer — see “Get Started” for setup.
Reading a missing key returns the zero value. Use the "comma ok" form to tell "missing" from "zero":
package main
import "fmt"
func main() {
ages := map[string]int{"ada": 36, "baby": 0}
if age, ok := ages["baby"]; ok {
fmt.Println("baby is", age)
}
if _, ok := ages["lin"]; !ok {
fmt.Println("lin not found")
}
}
Output
baby is 0 lin not found
Run this on your computer — see “Get Started” for setup.
Iterating in a stable order
Map iteration order is randomised on purpose. Sort the keys when output order matters:
package main
import (
"fmt"
"slices"
)
func main() {
prices := map[string]float64{"tea": 2.5, "coffee": 3, "cake": 4.25}
keys := make([]string, 0, len(prices))
for k := range prices {
keys = append(keys, k)
}
slices.Sort(keys) // Go 1.23+: keys := slices.Sorted(maps.Keys(prices))
for _, k := range keys {
fmt.Printf("%-7s %.2f\n", k, prices[k])
}
}
Output
cake 4.25 coffee 3.00 tea 2.50
Run this on your computer — see “Get Started” for setup.
A nil map can be read but panics when written — always create maps with make or a literal.
Test yourself
How do you check whether a key exists in a map?
m.has(key)v, ok := m[key]key in mm[key] != nil
Show answer
Answer: v, ok := m[key]
Practice next
- Two Sum · coding problem
- Group Anagrams · coding problem