package main
import "fmt"
// Number 声明类型约束
type Number interface {
int64 | float64 | string
}
func main() {
ints := map[string]int64{
"first": 34,
"second": 12,
}
floats := map[string]float64{
"first": 35.98,
"second": 26.99,
}
var a int64
a = 100
var b float64
b = 100.10
var c string
c = "100"
PrintNumber(a)
PrintNumber(b)
PrintNumber(c)
//fmt.Printf("Non-Generic Sums: %v and %v\n",
// SumInts(ints),
// SumFloats(floats))
fmt.Printf("Generic Sums: %v and %v\n",
SumIntsOrFloats[string, int64](ints),
SumIntsOrFloats[string, float64](floats))
// 调用泛型函数时省略类型参数,此时编译器从函数参数的类型推断类型参数。
// 调用没有参数的泛型函数,则需要在函数调用中包含类型参数
fmt.Printf("Generic Sums, type parameters inferred: %v and %v\n",
SumIntsOrFloats(ints),
SumIntsOrFloats(floats))
fmt.Printf("Generic Sums with Constraint: %v and %v\n",
SumNumbers(ints),
SumNumbers(floats))
}
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 SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V {
var s V
for _, v := range m {
s += v
}
return s
}
func SumNumbers[K comparable, V Number](m map[K]V) V {
var s V
for _, v := range m {
s += v
}
return s
}
func PrintNumber[V Number](number V) {
fmt.Println(number)
}
go学习笔记 - 1.18支持泛型
最新推荐文章于 2024-08-19 20:09:20 发布