Created
January 26, 2022 15:34
-
-
Save tuck1s/14d85c96e904d67bbf83edd6d8cc0094 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"constraints" | |
"fmt" | |
) | |
type Number interface { | |
constraints.Integer | constraints.Float | constraints.Complex | |
} | |
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, | |
} | |
// Initialize a map for the complex values | |
complexes := map[string]complex128{ | |
"first": 23 + 45i, | |
"second": 12 + 34i, | |
} | |
fmt.Printf("Generic Sums with Constraint: %v and %v and %v\n", | |
SumNumbers(ints), | |
SumNumbers(floats), | |
SumNumbers(complexes)) | |
} | |
// SumNumbers sums the values of map m. Its supports both integers | |
// and floats as map values. | |
func SumNumbers[K comparable, V Number](m map[K]V) V { | |
var s V | |
for _, v := range m { | |
s += v | |
} | |
return s | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Taking https://go.dev/doc/tutorial/generics on a little with constraints and complex numbers