Map lookup with comma-ok
- Version
- 1.27
- Review
- Draft
Summary#
Use value, ok := map[key] when a missing key must be distinguished from a stored zero value. The boolean records whether the key exists.
Syntax#
value, ok := counts[key]
Example#
package main
import "fmt"
func main() {
counts := map[string]int{"pear": 0}
pears, hasPears := counts["pear"]
plums, hasPlums := counts["plum"]
fmt.Println(pears, hasPears)
fmt.Println(plums, hasPlums)
}
Expected output#
0 true
0 false
Common mistakes#
A single-value map lookup returns the element type's zero value for a missing key. With a valid key, a nil map behaves like an empty map during lookup. If the key type is an interface, passing a slice or another non-comparable value as the key panics. Allocate the map before inserting entries.
Version applicability#
These lookup rules apply to Go 1.27 and earlier Go versions.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0