Detect missing keys with comma-ok
Detect missing keys with comma-ok
Reading m[key] returns the stored value or the zero value of the element type when the key is absent. Use v, ok := m[key] to distinguish an absent entry from a stored zero. The boolean ok is true exactly when the key exists.
package main
import "fmt"
func main() { m := map[string]int{"tea": 0} a, okA := m["tea"] b, okB := m["coffee"] fmt.Println(a, okA) fmt.Println(b, okB)}Both values are zero, but only tea exists. A check such as m[key] == 0 is insufficient to detect absence. Missing string values are empty strings, and missing bool values are false.
Expected output:
0 true0 falseUse a default when absent
package main
import "fmt"
func main() { m := map[string]int{"small": 0} for _, k := range []string{"small", "large"} { v, ok := m[k] if !ok { v = 10 } fmt.Println(k, v) }}The fallback is applied only for large. This code does not insert the fallback into the map. To store it, assign m[k] = v explicitly after deciding the desired policy.
Expected output:
small 0large 10Try it locally
Create a map of string to bool with "ready":false. Print value and existence for ready and missing.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Maps 02: Detect missing keys with comma-ok
Check the lesson objective before moving on.
What does ok mean in v, ok := m[k]?
What is the result of reading an absent key in map[string]int?