Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

practical way to set and sequentially increment a value inside a map?

Tags:

dictionary

go

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?

like image 818
Aleksandr Makov Avatar asked Dec 03 '22 23:12

Aleksandr Makov


1 Answers

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]
like image 145
icza Avatar answered Jan 07 '23 11:01

icza