Sum of values in a map using Golang | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
- 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?

7th Dec 2021, 10:53 PM
Robert Haugland
Robert Haugland - avatar
3 Antworten
+ 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)
7th Dec 2021, 11:56 PM
Solo
Solo - avatar
+ 1
Robert Haugland, Happy to help. Feel free to like and mark the best answers.
8th Dec 2021, 3:19 AM
Solo
Solo - avatar
0
Vasiliy, Thanks. Worked like a charm.
8th Dec 2021, 1:31 AM
Robert Haugland
Robert Haugland - avatar