Map comma-ok
v, ok := m[k] returns the value and a bool that is true only when k is in the map. Use it when the zero value of V is also a legitimate stored value.
Detailed Explanation
n := counts[path] is 0 both when the path is missing and when you stored a zero. For a counter that starts at zero, that coincidence is fine: counts[path]++ treats missing as zero and then writes 1. For a map of optional scores, or a cache where "" means "we looked up and the name is empty," you need the second result.
The form is ordinary multiple assignment. ok is false if the key is absent or if m is nil. v is the zero of V when ok is false. There is no third state. After delete(m, k), a later comma-ok is false.
When you can skip it. A map[string]struct{} used as a set only cares about presence: _, ok := set[name]. A map[string]int used as a counter can use m[k]++ without comma-ok. A map[string]*User can treat a nil pointer as "missing" only if you never store a nil *User on purpose; comma-ok is still clearer.
The same shape elsewhere. v, ok := x.(T) and v, ok := <-ch are cousins: two results, the second a bool. They are not maps, but readers recognize the pattern. Do not invent ok as a third return from your own functions unless it really is presence vs absence; an error is usually the better second result.
Range does not need comma-ok. for k, v := range m visits only present keys. A missing key never appears.
What it costs. One extra boolean. The hash lookup already happened. There is no reason to avoid comma-ok for performance. Avoid it only when the zero-value collision cannot occur and the shorter form reads better.
Code Examples
package main
import "fmt"
func main() {
scores := map[string]int{"a": 0}
v, ok := scores["a"]
fmt.Println(v, ok) // 0 true
v, ok = scores["b"]
fmt.Println(v, ok) // 0 false
}func has(set map[string]struct{}, name string) bool {
_, ok := set[name]
return ok
}func lookup(users map[string]*User, id string) (*User, bool) {
u, ok := users[id]
return u, ok
}
type User struct{ ID string }Common Gotchas
`ok` is false for a nil map, same as missing
you cannot distinguish "no map yet" from "empty map" with comma-ok alone.
Storing a zero still yields `ok == true`
that is the feature. Do not treat `v == 0` as missing.
There is no `m[k] = v, ok` write form
writes always set the key.