Go — Counting values with slices and maps
A Go map associates keys with values. In a writable map from strings to integers, a missing key reads as zero, so incrementing its entry counts its first occurrence.
A simple example
Look up one count
- Start with Key A has value 2
- Do this Look up A
- Result 2
package main
import "fmt"
func main() {
counts := map[string]int{"A": 2}
fmt.Println(counts["A"])
}
2
Count labels without relying on storage order
make creates a writable map. A lookup of a missing int key yields zero, so incrementing counts the first occurrence. A separate slice controls display order because map iteration order is unspecified.
A volunteer scans a red wristband, a blue one, then another red one. Increase the count for that colour on each scan. Look up red and blue by name when printing the totals.
Run the example
Go 1.20 or later. Run these commands from the directory containing the example.
go run main.go
package main
import (
"fmt"
)
func main() {
counts := make(map[string]int)
for _, color := range []string{"red", "blue", "red"} {
counts[color]++
}
for _, color := range []string{"red", "blue"} {
fmt.Println(color, counts[color])
}
}
red 2 blue 1
The first red contributes one count, blue contributes one, and the second red brings its count to two. Reading the red and blue keys in a specified order makes the report reproducible.
Try it yourself
Insert another blue before the last red. What changes?
Check your answer
Both keys now have a count of two. The requested display order stays red, then blue.