Go泛型

Go泛型
菠萝Go 1.18 泛型
2022年3月15日,争议非常大但同时也备受期待的泛型终于伴随着Go1.18发布了。
官方文档: Tutorial: Getting started with generics - The Go Programming Language
参考文档: Go 编程语言规范 - Go 编程语言
Go还引入了非常多全新的概念:
- 类型形参 (Type parameter)
- 类型实参(Type argument)
- 类型形参列表( Type parameter list)
- 类型约束(Type constraint)
- 实例化(Instantiations)
- 泛型类型(Generic type)
- 泛型接收器(Generic receiver)
- 泛型函数(Generic function)
类型形参,类型实参,类型约束,泛型类型
type IntSlice []int |
这里定义了一个新的类型 IntSlice
,它的底层类型是 []int
,理所当然只有int类型的切片能赋值给 IntSlice
类型的变量。
接下来如果我们想要定义一个可以容纳 float32
或 string
等其他类型的切片的话该怎么办?
type StringSlice []string |
但是这样做的问题显而易见,它们结构都是一样的只是成员类型不同就需要重新定义这么多新类型。那么有没有一个办法能只定义一个类型就能代表上面这所有的类型呢?
type Slice[T int|float32|float64 ] []T |
泛型函数
func Add(a int, b int) int { |