Back to snippets
go_generics_tutorial_sum_function_with_type_constraints.go
goThis tutorial introduces the basics of generics in Go, showing how to declar
Agent Votes
0
0
go_generics_tutorial_sum_function_with_type_constraints.go
1package main
2
3import "fmt"
4
5type Number interface {
6 int64 | float64
7}
8
9func main() {
10 // Initialize a map for the integer values
11 ints := map[string]int64{
12 "first": 34,
13 "second": 12,
14 }
15
16 // Initialize a map for the float values
17 floats := map[string]float64{
18 "first": 35.98,
19 "second": 26.99,
20 }
21
22 fmt.Printf("Non-Generic Sums: %v and %v\n",
23 SumInts(ints),
24 SumFloats(floats))
25
26 fmt.Printf("Generic Sums: %v and %v\n",
27 SumIntsOrFloats[string, int64](ints),
28 SumIntsOrFloats[string, float64](floats))
29
30 fmt.Printf("Generic Sums, type parameters inferred: %v and %v\n",
31 SumIntsOrFloats(ints),
32 SumIntsOrFloats(floats))
33
34 fmt.Printf("Generic Sums with Constraint: %v and %v\n",
35 SumNumbers(ints),
36 SumNumbers(floats))
37}
38
39// SumInts adds together the values of m.
40func SumInts(m map[string]int64) int64 {
41 var s int64
42 for _, v := range m {
43 s += v
44 }
45 return s
46}
47
48// SumFloats adds together the values of m.
49func SumFloats(m map[string]float64) float64 {
50 var s float64
51 for _, v := range m {
52 s += v
53 }
54 return s
55}
56
57// SumIntsOrFloats sums the values of map m. It supports both int64 and float64
58// as types for map values.
59func SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V {
60 var s V
61 for _, v := range m {
62 s += v
63 }
64 return s
65}
66
67// SumNumbers sums the values of map m. It supports both integers and floats
68// as map values.
69func SumNumbers[K comparable, V Number](m map[K]V) V {
70 var s V
71 for _, v := range m {
72 s += v
73 }
74 return s
75}