generics
This commit is contained in:
parent
f7047b5321
commit
e124226b07
3
go/genericz/go.mod
Normal file
3
go/genericz/go.mod
Normal file
@ -0,0 +1,3 @@
|
||||
module genericz
|
||||
|
||||
go 1.19
|
49
go/genericz/main.go
Normal file
49
go/genericz/main.go
Normal file
@ -0,0 +1,49 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func SumInts(m map[string]int64) int64 {
|
||||
var s int64
|
||||
for _, v := range m {
|
||||
s += v
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func SumFloats(m map[string]float64) float64 {
|
||||
var s float64
|
||||
for _, v := range m {
|
||||
s += v
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func SumMap[K comparable, V int64 | float64](m map[K]V) V {
|
||||
var s V
|
||||
for _, v := range m {
|
||||
s += v
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Initialize a map for the integer values
|
||||
ints := map[string]int64{
|
||||
"first": 34,
|
||||
"second": 12,
|
||||
}
|
||||
|
||||
// Initialize a map for the float values
|
||||
floats := map[string]float64{
|
||||
"first": 35.98,
|
||||
"second": 26.99,
|
||||
}
|
||||
|
||||
fmt.Printf("Non-Generic Sums: %v and %v\n",
|
||||
SumInts(ints),
|
||||
SumFloats(floats))
|
||||
|
||||
fmt.Printf("Generic Sums: %v and %v\n",
|
||||
SumMap[string, int64](ints),
|
||||
SumMap[string, float64](floats))
|
||||
}
|
Loading…
Reference in New Issue
Block a user