Go 泛型编程
go1.18 新增了对泛型的支持, 现在来看一个具体的使用场景:
假设有一个函数的功能是对输入的两个整数进行比较, 返回较大的那个。在go1.18之前的版本中, 可能写出如下的代码:
func Max(a, b int) int {
if a > b {
return a
}
return b
}
fun Max(a, b int8) int8 {
if a > b {
return a
}
return b
}
fun Max(a, b int16) int16 {
if a > b {
return a
}
return b
}
...
...
而引入泛型编程之后, 上述代码可以简化为如下形式:
func Max[T int | int8 | int16 | int32 | int64] (a, b T) T {
if a > b {
return a
}
return b
}
还可以将同一类型的数据封装到接口中:
package main
import "fmt"
type UInt interface {
uint | uint8 | uint16 | uint32 | uint64
}
type Int interface {
int | int8 | int16 | int32 | int64
}
type Float interface {
float32 | float64
}
// 组合三个接口和string类型
type DataType interface {
UInt | Int | Float | string
}
func Max[T DataType] (a, b T) T {
if a > b {
return a
}
return b
}
func main() {
fmt.Println(Max(1, 2))
fmt.Println(Max(1.0, 2.5))
// 按照字符串的字典序进行比较
fmt.Println(Max("Go", "Generic"))
}
输出如下:
了解了泛型的基本使用后, 下面我们仔细研究一下泛型。