GO / CHAPTER 04
Maps and presence checks
IntermediateDistinguish a stored zero from an absent map entry.
By the end of this chapter
- Initialize a writable map
- Use the comma-ok lookup
- Avoid assumptions about map iteration order
The idea
Enter with variables and collections understood. A map associates keys with values of declared types. Reading an absent key yields the value type’s zero value, which can be indistinguishable from a stored zero. The two-result lookup returns both the value and a boolean indicating presence. Use that form when absence affects behavior rather than treating every zero as a missing record.
A map created with make or a literal can accept entries. A nil map can be read, but assigning an entry to it panics. Map assignment shares the underlying map data rather than making an independent copy. Iteration order is unspecified, so tests and user interfaces must not rely on a particular traversal sequence. Collect and sort keys when deterministic presentation is required.
package main
import "fmt"
func main(){
stock:=map[string]int{"pen":0}
value,ok:=stock["pen"]
_,missing:=stock["book"]
fmt.Println(value,ok,missing)
}0 true false
The pen key exists despite its zero value. The book key is absent, so its presence flag is false.
Try it yourself
Count repeated words in a map and print one explicitly selected word’s count.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING