泛型
原创大约 2 分钟
为什么用泛型
package main
import "fmt"
// 泛型定义:[T int | float32]
// (a, b T):泛型声明
// T:返回一个泛型类型
func Add[T int | float32 | float64](a, b T) T {
return a + b
}
// 没有泛型时的做法
func Add2(a, b interface{}) interface{} {
switch a.(type) {
case int:
a = a.(int) + b.(int)
return a
case float32:
a = a.(float32) + b.(float32)
return a
case float64:
a = a.(float64) + b.(float64)
return a
}
return nil
}
func main() {
fmt.Println(Add(1, 2.1))
fmt.Println(Add2(1, 2))
}
泛型常见用法
package main
import "fmt"
// 用泛型自定义map
type MyMap[K int | string, V float32 | float64] map[K]V
// 有点Java的超类和子类那味儿了
type Man struct{}
type Woman struct{}
type Company[T Man | Woman] struct {
name string
ceo T
}
type MyChannel[T int | string] chan T
// 类型嵌套
type MyStruct[T int | string, V []T] struct {
Name T
Desc V
}
func main() {
m := MyMap[int, float32]{}
m[1] = 1.0
m[2] = 2.0
fmt.Println(m)
c := Company[Man]{
name: "google",
ceo: Man{},
}
fmt.Println(c)
ch1 := make(MyChannel[int], 10)
ch1 <- 1
fmt.Println(<-ch1)
ch2 := make(MyChannel[string], 10)
ch2 <- "hello"
fmt.Println(<-ch2)
}
泛型的错误用法
package main
import (
"fmt"
"reflect"
)
// 错误用法1:类型参数不能单独使用
type CommonType[T int | float32 | float64] T
// 正确用法:返回一个sliece的泛型
type CommonType[T int | float32 | float64] []T
// 错误用法2
type CommonType [T*int | float32 | float64][]T
// 正确用法
type CommonType[T interface{ *int } | float32 | float64] []T
// 通过反射判断泛型类型,但不建议在泛型中使用反射
func Add[T int | float32 | float64](a, b T) T {
value := reflect.ValueOf(a)
switch value.Kind() {
case reflect.Int:
fmt.Println("int type")
case reflect.Float32:
fmt.Println("float32 type")
default:
fmt.Println("unknown type")
}
return a + b
}
func main() {
// 匿名结构体不支持泛型
noname := struct[T int|string] {
name string
age int
}{}
// 泛型不支持类型判断,只有通过反射
switch T.(type) {
}
// 泛型不支持匿名函数
fn := func[T int | string](a, b T) {
fmt.Println("hello", a, b)
}()
}
感谢支持
更多内容,请移步《超级个体》。