Library contents

Go map lookup

Look up a product count and supply zero when the product is absent.

A simple example

map lookup

  1. Start with Map with A = 2
  2. Do this Read missing B with fallback 0
  3. Result 0
The lookup supplies zero because B has no stored value.

Syntax

Go syntax
map[string]int{"tea": 3}["coffee"]
Run these examples in Go

Save one example at a time as main.go. Use Go 1.21 or later.

go run main.go

Show a default when a product has no stock entry

A stock lookup can encounter a product with no recorded quantity. Supply the agreed fallback for display while keeping a missing catalog entry distinguishable from an actual update.

Result0
main.go
package main

import (
    "fmt"
)

func main() {
    fmt.Println(map[string]int{"tea": 3}["coffee"])
}
Output
0

Only tea has a recorded count. Looking up coffee returns the chosen default of zero.

Advertisements

Look up a borrowed tripod

The equipment desk has a two-day loan period for a camera, but no special period for a tripod. The system uses the recorded value when present and the displayed fallback otherwise. Which value reaches the screen?

Giventripod missing · default 7 days
Worked result7

Read a room preference

The timetable stores a room choice for the choir club. The system uses the recorded value when present and the displayed fallback otherwise. Which value reaches the screen?

Givenchoir → Hall · default Studio
Worked resultHall

What to watch for

A missing product and a recorded count of zero can mean different things. Check membership separately when that distinction matters.

Documentation for map lookup