78 lines
1.6 KiB
Go
78 lines
1.6 KiB
Go
package main
|
|
|
|
// extra resource: https://go.dev/doc/tutorial/generics
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"golang.org/x/exp/constraints"
|
|
)
|
|
|
|
// interfaces with type elements couldn't be used anywhere other than type paramaters
|
|
type Number interface {
|
|
int64 | float64
|
|
}
|
|
|
|
type Myint interface {
|
|
int64
|
|
}
|
|
|
|
func SumInt[K comparable, V Myint](m map[K]V) V {
|
|
var s V
|
|
for _, v := range m {
|
|
s += v
|
|
}
|
|
return s
|
|
}
|
|
|
|
func SumIntFloat[K comparable, V Number](m map[K]V) V {
|
|
var s V
|
|
for _, v := range m {
|
|
s += v
|
|
}
|
|
return s
|
|
}
|
|
|
|
func SumAll[K comparable, V constraints.Ordered](m map[K]V) V {
|
|
var s V
|
|
for _, v := range m {
|
|
s += v
|
|
}
|
|
return s
|
|
}
|
|
|
|
func main2() { // change main2 to main befor testing !!!
|
|
fmt.Println("Go functions can be written to work on multiple types using type parameters")
|
|
fmt.Println("square bracked types after function names are type paramaters")
|
|
fmt.Println("You can create type paramaters with keyword `comparable`(for comparable types), `any` for any type or other type name/s.")
|
|
fmt.Println("See differences between SumInt, SumIntFloat and SumAll")
|
|
fmt.Println("Please note down map keys should be comparable because of default map behaviour")
|
|
|
|
ints := map[string]int64{
|
|
"first": 1,
|
|
"second": 2,
|
|
"third": 3,
|
|
}
|
|
|
|
floats := map[string]float64{
|
|
"first": 1.23,
|
|
"second": 2.3123,
|
|
"third": 3,
|
|
}
|
|
|
|
strings := map[string]string{
|
|
"first": "str1",
|
|
"second": "str2",
|
|
"third": "str3",
|
|
}
|
|
|
|
fmt.Println(SumInt(ints))
|
|
// fmt.Println(SumInt(floats)) // error
|
|
fmt.Println(SumIntFloat(ints))
|
|
fmt.Println(SumIntFloat(floats))
|
|
// fmt.Println(SumIntFloat(strings)) // error
|
|
fmt.Println(SumAll(ints))
|
|
fmt.Println(SumAll(floats))
|
|
fmt.Println(SumAll(strings))
|
|
|
|
}
|