Golang:在地图内设置并顺序递增值的实用方法?

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
", 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?

Thanks.

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
", store)
}

Output (try it on the Go Playground):

map[bread:1]
map[bread:3]
map[bread:6]

The breadTotal variable is only a copy of the map integer value, you need to reference it as store["bread"] += num to increment the map integer value.

https://play.golang.org/p/LQzrbSZudH

package main

import (
    "fmt"
)

var store = map[string]int{}

func breadArrived(num int) {
    store["bread"] += num
    fmt.Printf("%v
", store)
}

func main() {
    breadArrived(1)
    breadArrived(2)
    breadArrived(3)
}

By the way, the first incrementing of the map integer works because go initializes everything to a default value, in the case of integers the default value is 0.

Simple increment like C\C++ style:

package main

import (
    "fmt"
)

var store = map[string]int{}

func main() {
    store["some_key"] = 0
    if _, found:= store["some_key"]; found{
        fmt.Println(store["some_key"])
        store["some_key"]++
        fmt.Println(store["some_key"])
    }
}

https://play.golang.org/p/nyM7GFI1-GW