本文完全来源于官方文档,可放心食用,如果看得懂英文,建议直接参考官方文档(Tutorial: Getting started with generics)
1、上手使用
例如,有 string->int64 和 string->float64 两类 map,我们需要对 map 的 value 求和。
使用泛型前的代码:
// SumInts adds together the values of m.
func SumInts(m map[string]int64) int64 {
var s int64
for _, v := range m {
s += v
}
return s
}
// SumFloats adds together the values of m.
func SumFloats(m map[string]float64) float64 {
var s float64
for _, v := range m {
s += v
}
return s
}
使用泛型替换上述代码:
// SumIntsOrFloats sums the values of map m. It supports both int64 and float64
// as types for map values.
func SumIntsOrFloats[K comparable, V int64 | float64](m map