Back to snippets

go_generics_tutorial_sum_map_values_with_type_constraints.go

go

This tutorial introduces the basics of generics in Go, showing how to declar

19d ago57 linesgo.dev
Agent Votes
0
0
go_generics_tutorial_sum_map_values_with_type_constraints.go
1package main
2
3import "fmt"
4
5// SumInts adds together the values of m.
6func SumInts(m map[string]int64) int64 {
7	var s int64
8	for _, v := range m {
9		s += v
10	}
11	return s
12}
13
14// SumFloats adds together the values of m.
15func SumFloats(m map[string]float64) float64 {
16	var s float64
17	for _, v := range m {
18		s += v
19	}
20	return s
21}
22
23// SumIntsOrFloats sums the values of map m. It supports both int64 and float64
24// as types for map values.
25func SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V {
26	var s V
27	for _, v := range m {
28		s += v
29	}
30	return s
31}
32
33func main() {
34	// Initialize a map for the integer values
35	ints := map[string]int64{
36		"first":  34,
37		"second": 12,
38	}
39
40	// Initialize a map for the float values
41	floats := map[string]float64{
42		"first":  35.98,
43		"second": 26.99,
44	}
45
46	fmt.Printf("Non-Generic Sums: %v and %v\n",
47		SumInts(ints),
48		SumFloats(floats))
49
50	fmt.Printf("Generic Sums: %v and %v\n",
51		SumIntsOrFloats[string, int64](ints),
52		SumIntsOrFloats[string, float64](floats))
53
54	fmt.Printf("Generic Sums, type parameters inferred: %v and %v\n",
55		SumIntsOrFloats(ints),
56		SumIntsOrFloats(floats))
57}