Slices, maps and strings · 3 MIN READ
Comma-ok is how you tell zero from missing
Report whether a key is present when its value can be zero.
The Tour's "Mutating Maps" page is the two-value read: elem, ok := m[key]. A missing key and a present zero look the same if you only take elem. Scores, counts, flags — anything whose zero is a legitimate stored value — need the ok.
delete(m, key) is the other half of that page. Deleting a missing key is a no-op, not an error. After delete, ok is false even if the old value was zero.
SEE THE IDEA
Presence is a second result
- 01
Stored zero
gom["known"] = 0value is 0; ok is true
- 02
Absent entry
gov, ok := m["absent"]value is 0; ok is false
- 03
Decision
goif !ok { ... }Handle absence explicitly
The boolean answers whether the key exists, independently of the value.
In practice
Use comma-ok when zero is a meaningful stored value. The same pattern appears in type assertions and channel receives, but the boolean answers a different presence question in each case. Give it a name such as found when that improves the branch.
Watch out
Testing v == 0 cannot distinguish an absent key from an entry explicitly containing zero.
Work through the exercise
package main
// Has reports whether key is in m, even when m[key] is 0.
func Has(m map[string]int, key string) bool {
return m[key] != 0
}
func main() {}Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.
Progress stays in this browser. No account needed.