package main
import (
"fmt"
)
var store = map[string]int{}
func breadArrived(num int) {
if breadTotal, ok := store["bread"]; ok {
breadTotal += num
} else {
store["bread"] = num
}
fmt.Printf("%v\n", store)
}
func main() {
breadArrived(1)
breadArrived(2)
breadArrived(3)
}
Code above ignores the +=
operator, so store["bread"]
always equals to 1
. I assume I'm missing something like "passing by reference" here. Also, is there any more convenient way of doing this?
You're only incrementing the breadTotal
local variable, and not the value in the store
map. It should be:
store["bread"] = breadTotal + num
Also you can simply do:
store["bread"] += num
Also since indexing a map returns the zero value of the value type for keys which are not yet in the map (zero value for int
is 0
– properly telling no bread yet), that if
is completely unnecessary. You can simply do:
func breadArrived(num int) {
store["bread"] += num
fmt.Printf("%v\n", store)
}
Output (try it on the Go Playground):
map[bread:1]
map[bread:3]
map[bread:6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With