Skip to content

Instantly share code, notes, and snippets.

@tuck1s
Created January 26, 2022 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuck1s/14d85c96e904d67bbf83edd6d8cc0094 to your computer and use it in GitHub Desktop.
Save tuck1s/14d85c96e904d67bbf83edd6d8cc0094 to your computer and use it in GitHub Desktop.
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
}
@tuck1s
Copy link
Author

tuck1s commented Jan 26, 2022

Taking https://go.dev/doc/tutorial/generics on a little with constraints and complex numbers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment