find the sum of all keys in a map in go

To find the sum of all keys in a map in Go, we need to iterate over the keys of the map and add up their values. Here is an example code snippet that demonstrates how to achieve this:

main.go
func sumKeys(m map[string]int) int {
    sum := 0
    for key := range m {
        sum += m[key]
    }
    return sum
}
120 chars
8 lines

In the sumKeys function, we declare a variable sum to keep track of the running total of key values. Then we use a range loop to iterate over each key in the map m, adding its value to the sum variable.

To use this function, we would pass in a map with string keys and int values, like so:

main.go
testMap := map[string]int{"abc": 1, "def": 2, "ghi": 3}
sum := sumKeys(testMap)
fmt.Println(sum) // Output: 6
110 chars
4 lines

related categories

gistlibby LogSnag