Go Maps
A map stores key–value pairs and lets you look up a value by its key very quickly. Other languages call this a dictionary, hash map or associative array. The type is written map[KeyType]ValueType — for example map[string]int maps names to numbers.
Keys must be comparable with ==: strings, numbers, booleans, pointers, arrays and structs of comparable fields work; slices, maps and functions cannot be keys.
Creating a map
package main
import "fmt"
func main() {
// map literal
capitals := map[string]string{
"France": "Paris",
"Japan": "Tokyo",
"Peru": "Lima",
}
// empty map, ready to use
ages := make(map[string]int)
ages["Tom"] = 31
ages["Ivy"] = 27
fmt.Println(capitals["Japan"])
fmt.Println(len(capitals), len(ages))
fmt.Println(ages) // fmt prints maps with sorted keys
}Tokyo
3 2
map[Ivy:27 Tom:31]
Note:
fmtsorts keys when it prints a whole map, which makes printed maps look ordered. Afor rangeloop over a map does not — its order is random.
Reading, writing and deleting
| Operation | Syntax |
|---|---|
| Insert or update | m[key] = value |
| Read | v := m[key] (zero value if missing) |
| Read and check | v, ok := m[key] |
| Delete | delete(m, key) (no error if missing) |
| Count | len(m) |
| Remove everything | clear(m) |
Reading a missing key does not fail — it returns the zero value. Use the comma-ok form to tell "missing" apart from "present with a zero value".
package main
import "fmt"
func main() {
stock := map[string]int{"apples": 5, "pears": 0}
fmt.Println(stock["apples"], stock["pears"], stock["mangos"])
if qty, ok := stock["pears"]; ok {
fmt.Println("pears are tracked, quantity", qty)
}
if _, ok := stock["mangos"]; !ok {
fmt.Println("mangos are not tracked")
}
stock["apples"] += 10 // update using the current value
delete(stock, "pears")
fmt.Println(stock, len(stock))
}5 0 0
pears are tracked, quantity 0
mangos are not tracked
map[apples:15] 1
Iterating in a predictable order
Go randomises map iteration order on purpose, so programs don't accidentally rely on it. When order matters, sort the keys first.
package main
import (
"fmt"
"slices"
"strings"
)
func main() {
text := "the cat and the hat and the bat"
counts := map[string]int{}
for _, w := range strings.Fields(text) {
counts[w]++ // missing keys start at 0
}
words := make([]string, 0, len(counts))
for w := range counts {
words = append(words, w)
}
slices.Sort(words)
for _, w := range words {
fmt.Printf("%-4s %d\n", w, counts[w])
}
}and 2
bat 1
cat 1
hat 1
the 3
Nil maps
The zero value of a map type is nil. A nil map behaves like an empty map for reading, but writing to it panics. Always create maps with a literal or make before storing values.
package main
import "fmt"
func main() {
var prices map[string]float64
fmt.Println(prices == nil, len(prices), prices["tea"])
defer func() {
fmt.Println("recovered:", recover())
}()
prices["tea"] = 2.5 // panics
}true 0 0
recovered: assignment to entry in nil map
Maps are references
Assigning a map to another variable or passing it to a function does not copy it — both names refer to the same data. Use maps.Clone for an independent copy.
package main
import (
"fmt"
"maps"
)
func addBonus(scores map[string]int) {
for name := range scores {
scores[name] += 5
}
}
func main() {
scores := map[string]int{"Ann": 80, "Bo": 72}
alias := scores
snapshot := maps.Clone(scores)
addBonus(scores)
alias["Cy"] = 90
fmt.Println(scores)
fmt.Println(snapshot)
}map[Ann:85 Bo:77 Cy:90]
map[Ann:80 Bo:72]
Maps with struct values
Values can be any type, including structs and slices — a common way to group data.
package main
import "fmt"
type Employee struct {
Name string
Dept string
}
func main() {
staff := []Employee{
{"Ada", "eng"}, {"Lin", "ops"}, {"Max", "eng"}, {"Sol", "sales"},
}
byDept := map[string][]string{}
for _, e := range staff {
byDept[e.Dept] = append(byDept[e.Dept], e.Name)
}
fmt.Println(byDept)
}map[eng:[Ada Max] ops:[Lin] sales:[Sol]]
Test yourself
What does m["missing"] return for a map[string]int without that key?
nil- It panics
0, the zero value-1
What happens when you write to a nil map?
- The map is created automatically
- It panics
- Nothing
- Compile error
How can you print a map's entries in a guaranteed order inside a loop?
- Use
range— it is always sorted - Collect and sort the keys, then loop over them
- Call
m.Sort() - Use
sorted range