You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
package main
import"fmt"typeNumberinterface {
int64|float64
}
// SumIntsOrFloats sums the values of map m. It supports both int64 and float64// as types for map values.funcSumIntsOrFloats[Kcomparable, VNumber](mmap[K]V) V {
varsVfor_, v:=rangem {
s+=v
}
returns
}
// IF 模仿三目运算funcIF[Vany](flagbool, a, bV) V {
ifflag {
returna
}
returnb
}
funcmain() {
// Initialize a map for the integer valuesints:=map[string]int64{
"first": 34,
"second": 12,
}
// Initialize a map for the float valuesfloats:=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、vscode
cmd + shift + p
3、选择
Go: Install/Update Tools
勾选更新所有工具REF
https://go.dev/doc/tutorial/generics
https://go.dev/blog/go1.18
The text was updated successfully, but these errors were encountered: