Map Lookup Ok Separates Missing From Zero

The two-result map lookup tells a missing key apart from a key stored with its zero value, which plain indexing cannot do.

GoData Integrity

Code

gosnippet
25 lines
package main

import "fmt"

func main() {
	stock := map[string]int{
		"apple": 0,
		"pear":  12,
	}

	// ok separates a missing key from a key stored with its zero value
	quantity, ok := stock["apple"]
	fmt.Println("apple:", quantity, "present:", ok)

	quantity, ok = stock["pear"]
	fmt.Println("pear: ", quantity, "present:", ok)

	quantity, ok = stock["kiwi"]
	fmt.Println("kiwi: ", quantity, "present:", ok)

	// check presence without writing a default into the map
	if _, exists := stock["kiwi"]; !exists {
		fmt.Println("kiwi is not stocked")
	}
}

What the code does

What another module actually calls is the function main — everything else is wiring.

Watch out for

  • The dependency list is empty — the language runtime already provides everything.

Applying it

The primary signature, spelled out, is func main()

Look for the apple:, pear:, kiwi: prefixes as the file executes; they connect every printed line to the step behind it.

Statements that matter most here

quantity, ok := stock["apple"]

Interactive Tools for This Topic

FAQ

What does Map Lookup Ok Separates Missing From Zero print when run?
Invoke the file as-is — the `apple:`, `pear:`, `kiwi:` prefixes identify which step printed each line.