Appearance
泛型
- 泛型的核心是类型参数(Type Parameters),它允许你在定义函数或类型时指定 “类型占位符”,使用时再替换为具体类型。
泛型函数
- 格式:
func 函数名[类型参数 泛型类别](参数列表) 返回值列表 { 函数体 }
go
// 定义一个泛型函数,参数为一个类型参数 T
func printType[T any](value T) {
fmt.Printf("Type of value: %T\n", value)
}泛型类别
any
any是一个特殊的类型约束,它表示任意类型。- 格式:
func 函数名[类型参数 any](参数列表) 返回值列表 { 函数体 }
go
func printType[T any](value T) {
fmt.Printf("Type of value: %T\n", value)
}comparable
comparable是一个类型约束,它表示可以使用==和!=运算符进行比较的类型。- 格式:
func 函数名[类型参数 comparable](参数列表) 返回值列表 { 函数体 }
go
func compare[T comparable](a, b T) bool {
return a == b
}联合约束
go
type MyConstraint interface {
int | int64 | float64 | float32
}
func test1[T MyConstraint](a T, b T) bool {
return a == b
}自定义约束
go
// 自定义类型约束
type MyConstraint interface {
String() string
}
type MyStruct struct {
Name string
Age int
}
func (m MyStruct) String() string {
return fmt.Sprintf("Name: %s, Age: %d", m.Name, m.Age)
}
func test2[T MyConstraint](a T) string {
return a.String()
}
newMyStruct := MyStruct{Name: "张三", Age: 18}
fmt.Println(test2(newMyStruct))泛型结构体
go
type Stack[T any] struct {
ele []T
}
func (s *Stack[T]) Push (i T) {
s.ele = append(s.ele, i)
}
func (s *Stack[T]) IsEmpty () bool {
return len(s.ele) == 0
}