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

  1. 01

    Stored zero

    go
    m["known"] = 0

    value is 0; ok is true

  2. 02

    Absent entry

    go
    v, ok := m["absent"]

    value is 0; ok is false

  3. 03

    Decision

    go
    if !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.

Official reference ↗

Work through the exercise

go
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() {}
Try it yourself

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.