| 1 | package main |
| 2 | |
| 3 | import "fmt" |
| 4 | |
| 5 | // SumIntsOrFloats sums the values of map m. It supports both int64 and float64 |
| 6 | // as types for map values. |
| 7 | func SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V { |
| 8 | var s V |
| 9 | for _, v := range m { |
| 10 | s += v |
| 11 | } |
| 12 | return s |
| 13 | } |
| 14 | |
| 15 | func main() { |
| 16 | // Initialize a map for the integer values |
| 17 | ints := map[string]int64{ |
| 18 | "first": 34, |
| 19 | "second": 12, |
| 20 | } |
| 21 | |
| 22 | // Initialize a map for the float values |
| 23 | floats := map[string]float64{ |
| 24 | "first": 35.98, |
| 25 | "second": 26.99, |
| 26 | } |
| 27 | |
| 28 | fmt.Printf("Generic Sums: %v and %v\n", |
| 29 | SumIntsOrFloats[string, int64](ints), |
| 30 | SumIntsOrFloats[string, float64](floats)) |
| 31 | } |
| 32 | |
| 33 | // Output: |
| 34 | // Generic Sums: 46 and 62.97 |