package main
import "fmt"
type Number interface {
int64 | float64
}
// SumIntsOrFloats sums the values of map m. It supports both int64 and float64
// as types for map values.
func SumIntsOrFloats[K comparable, V Number](m map[K]V) V {
var s V
for _, v := range m {
s += v
}
return s
}
// IF 模仿三目运算
func IF[V any](flag bool, a, b V) V {
if flag {
return a
}
return b
}
func main() {
// Initialize a map for the integer values
ints := map[string]int64{
"first": 34,
"second": 12,
}
// Initialize a map for the float values
floats := map[string]float64{
"first": 35.98,
"second": 26.99,
}
fmt.Printf("Generic Sums: %v and %v\n",
SumIntsOrFloats[string, int64](ints),
SumIntsOrFloats[string, float64](floats))
fmt.Printf("Generic Sums, type parameters inferred: %v and %v\n",
SumIntsOrFloats(ints),
SumIntsOrFloats(floats))
fmt.Printf("IF: %+v", IF[int](true, 1, 2))
}
如何理解泛型
有几个关键点:
我们要在 [ ] 中为泛型函数声明它支持的类型(类型约束) func SumIntsOrFloats[K comparable, V Number](m map[K]V) V
示例
如何理解泛型
有几个关键点:
类型约束
)func SumIntsOrFloats[K comparable, V Number](m map[K]V) V
IF[int](true, 1, 2)
,IF(true, 1, 2)
类型约束
新增类型
为了方便泛型使用,新增了两个类型 any 和 comparable,不过这两种类型都只能用于参数
类型约束
不能用于声明变量。vscode 如何尝试 generics
1、到官网下载安装
go1.18
2、vscodecmd + shift + p
3、选择Go: Install/Update Tools
勾选更新所有工具REF
https://go.dev/doc/tutorial/generics https://go.dev/blog/go1.18