Skip to the workspace
Pebellslearn by building
Maps & Structs  ›  Lesson

The Comma-Ok Idiom

Comma-Ok Idiom 12 minThe comma-ok form returns a value and a boolean. A map lookup reports key presence, a type assertion reports success, and a channel receive reports whether the value was sent before closure.

golang / The Comma-Ok Idiom

Explore each scene at your own pace.

01 · The rule

The rule

The Comma-Ok Idiom

The comma-ok form returns a value and a boolean. A map lookup reports key presence, a type assertion reports success, and a channel receive reports whether the value was sent before closure.

Distinguish a missing entry from an entry that stores the type's zero value.

tally gains a feature: it remembers the line on which each word last appeared, with lines numbered from 0. Now lastLine["go"] returns 0 — but did "go" appear on the first line, or never at all? The zero value that made counting easy has become ambiguous. Go's answer is a second return value.

The rule

Ask for ok whenever zero could be a real answer.

Any map lookup can return two values:

line, ok := lastLine["go"]
  • line is the stored value, or the zero value if the key is absent.
  • ok is true if the key is present, false if not — regardless of what the value is.
lastLine := map[string]int{"tally": 0}

n, ok := lastLine["tally"] // 0 true  — present, on line 0
m, ok2 := lastLine["go"]   // 0 false — absent

The usual shape puts it in an if header, so the variables live only where they matter:

if line, ok := lastLine[w]; ok {
	fmt.Printf("%q last seen on line %d\n", w, line)
} else {
	fmt.Printf("%q never appears\n", w)
}

If you only care about presence, discard the value: _, seen := lastLine[w].

The same two-value pattern — hence the name "comma ok" — appears in two other places you will meet later:

  • Type assertions: s, ok := v.(string). Without ok, a wrong type panics; with it, you get ok == false instead.
  • Channel receives: v, ok := <-ch. ok is false once the channel is closed and empty.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.