Go Basics: Distinguish Missing Map Keys from Zero Values
An inventory count of zero means something different from an unknown product. Keep that distinction when reading a Go map, and sort keys before producing a stable report.
Prepare a scratch directory
Tested on Linux amd64 with Go 1.26.10. Install Go and make go available on PATH. You also need Bash, a text editor, and the standard mktemp, rm, and rmdir utilities. The example uses only the standard library and needs no module or external dependency.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save this as map-presence-demo.go:
package main
import (
"fmt"
"sort"
)
func main() {
stock := map[string]int{"tea": 0, "coffee": 8}
for _, name := range []string{"tea", "water"} {
count, exists := stock[name]
fmt.Printf("%s: count=%d exists=%t\n", name, count, exists)
}
stock["water"] = 3
delete(stock, "coffee")
keys := make([]string, 0, len(stock))
for name := range stock {
keys = append(keys, name)
}
sort.Strings(keys)
for _, name := range keys {
fmt.Printf("%s=%d\n", name, stock[name])
}
var empty map[string]int
fmt.Println("Nil map read:", empty["tea"], len(empty))
}Run it:
go run map-presence-demo.goObserved output:
tea: count=0 exists=true
water: count=0 exists=false
tea=0
water=3
Nil map read: 0 0Read the result
Both the missing key and the present zero count return 0 as their value. The second lookup result tells them apart. Sorting an extracted key list keeps the report deterministic; Go does not promise map iteration order. Reading a nil map is safe and returns the value type’s zero value.
Apply it carefully
Writing to a nil map panics: initialize it with make or a map literal first. Ordinary maps also need synchronization when writes overlap other accesses from different goroutines. Sorting keys solves presentation order, not concurrency.
The official Go reference documents the behavior used here.
Clean up
Remove the saved source, return to the starting directory, and remove the empty practice directory. go run does not leave an executable here; Go manages its build cache separately.
rm -- map-presence-demo.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.