find the sum of all values in a map in go

One way to find the sum of all values in a map in Go is to loop through the map and add up the values using a loop. Here's an example code snippet to do that:

main.go
// Define a map
m := map[string]int{
    "a": 1,
    "b": 2,
    "c": 3,
}

// Initialize a variable to hold the sum
sum := 0

// Loop through the map and add up the values
for _, v := range m {
    sum += v
}

// Print the sum
fmt.Println(sum) // Output: 6
258 chars
18 lines

In this example, we define a map called m with string keys and integer values. We initialize a variable called sum to hold the sum of the values. We then loop through the map using a for loop, using the _ identifier to ignore the keys since we only care about the values. Inside the loop, we add up the values to the sum variable. Finally, we print out the sum variable which gives us the total sum of all the values in the map.

related categories

gistlibby LogSnag