今天继续学习 Go 1.18引入的 泛型 ,我们将以Go官方的泛型教程为资料,每天利用几分钟的时间来学习,慢慢积累。
昨天我们定义了一个泛型函数,代码如下:
// 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[K]V) V {
var s V
for _, v := range m {
s += v
}
return s
}
在定义泛型函数时,需要为泛型参数指定 类型约束(type constraint) 来限制泛型参数类型的范围。 SumIntsOrFloats 函数名称后边中括号的内容 [K comparable, V int64 | float64] 就是类型约束。
今天来学习如何把之前定义的类型约束移动到一个接口定义中,这样就能在多个地方重复使用。 使用接口来声明类型约束的方式,可以在约束条件比较复杂的场景下简化代码。
将类型约束声明为接口
当把一个类型约束声明为接口时,这个接口就成为了一个约束接口,约束接口可以用来指定特定的类型。
下面将泛型函数 func SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V 中泛型参数V的类型约束声明为一个接口:
type Number interface {
int64 | float64
}
在这段代码中,在Number接口定义的内容声明了一个 int64 | float64 的类型约束,这样泛型函数 SumIntsOrFloats 中泛型参数V的类型约束可以直接使用 Number 。
type Number interface {
int64 | float64
}
func SumIntsOrFloats[K comparable, V Number](m map[K]V) V {
var s V
for _, v := range m {
s += v
}
return s
}
至此,在两天内,我们使用2个5分钟时间,基于Go官方的tutorial,对泛型做了一个基本的入门。