久等的泛型终于在Go语言中提供了支持, 所以赶快体验一下泛型的舒适.
- Go版本1.17.1
- 运行命令: go run -gcflags=-G=3 main.go
1
2
3
4
5
6
|
type Addable interface {
type int, int8, int16, int32, int64
}
func add[T Addable](x, y T)T{
return x + y
}
|
1
2
3
4
5
6
7
8
|
type myMap[T any] struct {
m map[int]T
}
func newMyMap[T any](size int)*myMap[T]{
return &myMap[T]{
m: make(map[int]T, size),
}
}
|
1
2
3
|
ss := newMyMap[string](1)
ss.m[1] = "hello"
fmt.Println(ss)
|
1
2
3
4
5
|
func testGeneric[R any](array []R) {
for _, e := range array {
fmt.Println(e)
}
}
|
1
|
testGeneric([][]int{[]int{1, 2, 3}, []int{4, 5, 6}, []int{7, 8, 9}})
|
1
2
3
|
[1 2 3]
[4 5 6]
[7 8 9]
|
注意:无法从赋值语句中自动推断类型
1
2
3
|
func newMap[V any]() map[int]V {
return make(map[int]V, 0)
}
|
1
2
|
var myMap map[int]string = newMap()
fmt.Println(myMap)
|
1
|
./main.go:206:35: cannot infer V (/Path/To/main.go:224:13) ([<nil>])
|
1
2
3
|
func newMap[V any]() map[int]V {
return make(map[int]V, 0)
}
|
1
2
|
var myMap = newMap[string]()
fmt.Println(myMap)
|
1
2
3
|
func PointerOf[V any](value V) *V {
return &value
}
|
1
2
|
p := PointerOf(1)
fmt.Println(p)
|