- 1
Sum of values in a map using Golang
If I have a map in Golang like: m = {"p1":2.4, "p2":1.5, "p3":1.7} Now want to obtain the sum of just the values in map m. How is this done? I know to loop through an array to get the sum: array = [2.4, 1.5, 1.7] sum := 0 for i := 0; i <= len(array); i++{ sum += i fmt.Println(sum) How do I write this for a map using Golang?
3 Réponses
+ 3
var sum float32 = 0
m := map[string]float32{
"p1":2.4, "p2":1.5, "p3":1.7}
for _,val := range m {
sum += val
}
fmt.Println(sum)
+ 1
Robert Haugland, Happy to help. Feel free to like and mark the best answers.
0
Vasiliy,
Thanks. Worked like a charm.