Go 1.17 泛型！

示例代码

```package main

import "fmt"

type Number interface{
type int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64,
float32, float64
}

func max[T Number](a, b T) T {
if a > b {
return a
}
return b
}

func main() {
fmt.Println(max(float64(1), float64(2)))
}
```

```\$ go run -gcflags=-G=3 main.go
2
```

语法

泛型定义

```type Number interface{
type int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64,
float32, float64
}
```

泛型声明

```func max[T Number](a, b T) T {
if a > b {
return a
}
return b
}
```

```func max[T any](a, b T) T {
if a > b {
return a
}
return b
}
```

```template <class T>
void swap(T &a, T &b) {
T temp;
temp = a;
a = b;
b = temp;
}
```

泛型调用

```fmt.Println(max(float64(1), float64(2)))
fmt.Println(max[float64](1, 2))
```

一些其他的测试

多个类型与主动声明类型

```package main

import "fmt"

type Number interface{
type int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64,
float32, float64
}

type Float interface{
type float32, float64
}

func max[T Number, T2 Float] (a, b T) T {
var ll T = 1
var ll2 T2 = 3
fmt.Printf("%+v %T %+v %T ", ll, ll, ll2,ll2)
if a > b {
return a
}
return b
}

func main() {
fmt.Println(max[float64, float64](1, 2))
}
```

```1 float64 3 float64 2
```

错误的类型

```package main

import "fmt"

type Number interface{
type int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64,
float32, float64, string
}

func max[T Number] (a, b T) T {
if a > b {
return a
}
return b
}

func main() {
fmt.Println(max(1, 2))
}
```

```2
```

泛型类

```package main

import "fmt"

type Number interface{
type int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64,
float32, float64, string
}

type container [T Number]struct {
l []T
}

func newContainer[T Number] () container[T]  {
return container [T]{
l : make([]T, 0),
}
}

func (c container [T])Append(x T) {
c.l = append(c.l, x)
}

func main() {
c := newContainer[int]()
c.Append(1)
fmt.Printf("%+v, %T, %T", c, c, c.l)
}
```

```{l:[]}, main.container[int], []int
```