泛型
go1.18版本开始支持
在函数上使用[T 支持的类型] 表示泛型,比如
func AddSum[T int|float64](params ...T)(sum T){
// 一些操作
return sum
}
自带泛型:
- any 表示任何类型,即interface
- comparable 表示可以被比较的类型
comparable is an interface that is implemented by all comparable types
(booleans, numbers, strings, pointers, channels, arrays of comparable types,
structs whose fields are all comparable types).
The comparable interface may only be used as a type parameter constraint,
not as the type of a variable.
就个人而言,泛型的使用倒是可以解决不同类型的相同函数的编写,但是对于其其它妙用还不太明确,需要慢慢体会
在函数上申明多个类型约束
// 1. 泛型的类型限制,在函数上直接申明该函数支持的多个类型
func AddElem[T int | string](params []T) (sum T) {
for _, elem := range params {
sum += elem
}
return
}
func TestGenerics_AddElem(t *testing.T) {
// 1. 在函数上声明泛型支持的多个类型
// 1.1 传入支持的int
intSum := AddElem([]int{
1, 2, 3, 4, 5, 6, 7, 8, 9})
t.Logf("测试1.1: 类型=%T,val=%+v", intSum, intSum)
// 1.2 传入支持的string
strSum := AddElem([]string{
"静", "以", "修", "身", ",", "俭", "以", "养", "德"})
t.Logf("测试1.2: 类型=%T,val=%+v", strSum, strSum)
// 1.3 传入不支持的类型 ./generics_test.go:29:24: float64 does not implement int|string