package main import "fmt" //普通函数 func same(a, b string) bool { return a == b } //添加泛型 func same1[T int | float64 | string](a, b T) bool { return a == b } //普通结构体 type Person struct { Name string Sex int } //泛型结构体 type Person1[T any] struct { Name string Sex T } //map泛型 两个一样 comparable 可以理解为any //type TMap[K string | int, V string | int] map[K]V type TMap[K comparable, V string | int] map[K]V //泛型切片 type TSlice[S any] []S //使用 type MyType interface { int | float64 | string | int32 | int64 } func Test[T MyType](s T) { fmt.Println("s=", s) } type MyType1 interface { ~int | int64 } type MyInt1 int func test1[T MyType1](t T) { fmt.Println("t=", t) } func main() { b := same("a", "b") fmt.Println("b=", b) // 错误 这时候就需要泛型 //b1 := same(1, 2) //fmt.Println("b=", b1) // 使用泛型 b1 := same1(1.2, 1.6) // ==> b1 := same1[float](1.2, 1.6) fmt.Println("b=", b1) //泛型结构体 p := Person1[int]{} p.Name = "123" p.Sex = 456 //int p1 := Person1[string]{} p1.Name = "123" p1.Sex = "456" //string //map泛型 m := make(TMap[string, string]) m["yanghao"] = "yh" m1 := make(TMap[int, string]) m1[132] = "yh" //泛型切片 s := make(TSlice[string], 6) s[5] = "456" s1 := make(TSlice[int], 6) s1[5] = 123 // 使用自定义泛型 Test("123") Test(123) Test(1.23) test1[int](1231) test1[MyInt1](1231) //~ 格式不严格 如果不使用就会报错 }