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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.