package main
import (
"fmt"
)
/**
泛型的使用,泛型方法不允许暴露(泛型只能在同一个包中使用,所以要注意大小写),感觉没有什么卵用
*/
//泛型方法定义
func gpTe[T any](i T) T {
return i
}
//泛型结构体定义
type my[T any] struct {
Name T
}
//泛型切片
type myc[T any] []T
//*泛型Map,这里需要注意,定义泛型Map时需要为Key设置类型约束
//先定义了一个约束
//使用interface进行约束
type MyType interface{
type string, int, bool
}
//之后定义了一个泛型Map
type myMap[K MyType, V any] map[K]V
// *使用func进行约束。泛型约束为 实现了getValue()函数的结构体
type Mytype2 interface {
getValue() string
}
// tt实现了getValue()方法,所以Mytype2 对应的地方可以使用tt
type tt struct {
Name string
}
//如果为*tt则会报错
func (t tt) getValue() string {
return t.Name
}
//之后定义了一个泛型方法。上面的Mytype2约束了gpFunc方法
func gpFunc[T Mytype2](t T) {
fmt.Println(t.getValue())
}
//也可以将两种约束混用(type+接口的混合使用)。既要满足string, int, bool其中之一,也要满足实现了getValue() string方法
type myType3 interface{
type string, int, bool
getValue() string
}
//为struct绑定的泛型方法
type mytstruct[T any] struct {
Name string
}
func (m mytstruct[T]) gpSF(t T) T {
return t
}
func main() {
//需要在Go Tool Arguments中增加:-gcflags=-G=3,否则会报错
fmt.Println(gpTe[string]("123") + "456")
my := my[string]{
Name: "qin",
}
fmt.Println(my)
//这里不要写成:i := []myc[string]{"这是一个泛型切片"}
i := myc[string]{"这是一个泛型切片"}
fmt.Println(i)
c := make(myMap[string, int])
c["test"] = 1
fmt.Println(c)
temp := tt{"test2"}
gpFunc[tt](temp)
mystruct := mytstruct[string]{"为struct绑定的泛型方法"}
fmt.Println(mystruct.gpSF("测试成功"))
}
Golang泛型的使用
于 2022-07-07 23:23:21 首次发布