Go Update after comma-ok lookup
Decrease a stock balance only when the product is already on the ledger.
A simple example
Update after comma-ok lookup
- Start with A = 3
- Do this Subtract 1 for existing A
- Result A = 2
Syntax
n, exists := stock[item]
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goReduce only the stock that is on the ledger
A storeroom issues one mug and receives a request for an unlisted bowl. The clerk should reduce the mug balance but leave the unlisted product out of the ledger.
package main
import (
"fmt"
)
func main() {
stock := map[string]int{"Mug": 3}
for _, item := range []string{"Mug", "Bowl"} {
if n, exists := stock[item]; exists {
stock[item] = n - 1
}
}
fmt.Println(stock["Mug"])
}
2
Mug falls from three to two. The unlisted Bowl receives no mapping.
Issue paintbrushes
A class has fourteen brushes under its art-room key. An existing stock record is reduced by the number handed out. What value is written back under the same key?
Update a mug count
The café has eight cups on its stock card. An existing stock record is reduced by the number handed out. What value is written back under the same key?
What to watch for
Decrementing stock[item] without checking for the key can insert a negative count for an unlisted item.