在Go 1.18+中,类型约束主要有以下几种形式:
1. 预声明约束
any - 任何类型(interface{}的别名)
comparable - 可比较类型(支持 == 和 !=)
2. 接口约束
可以定义自定义接口作为约束:
// 基本接口约束
type Number interface {
int | int8 | int16 | int32 | int64 |
uint | uint8 | uint16 | uint32 | uint64 |
float32 | float64
}
// 方法集接口约束
type Stringer interface {
String() string
}
// 复合约束
type Ordered interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64 |
~string
}
3. 联合类型约束
使用 | 运算符组合多个类型:
type Numeric interface {
int | float64
}
func Add[T Numeric](a, b T) T {
return a + b
}
4. 近似约束
使用 ~ 符号匹配底层类型:
type MyInt int
type Integer interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
func Process[T Integer](value T) {
// MyInt 也满足此约束
}
小于函数实现
对于小于函数,需要定义 Ordered 约束:
package main
import "fmt"
type Ordered interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64 |
~string
}
func Less[T Ordered](a, b T) bool {
return a < b
}
func main() {
fmt.Println(Less(1, 2)) // true
fmt.Println(Less(3.14, 2.71)) // false
fmt.Println(Less("a", "b")) // true
type MyInt int
fmt.Println(Less(MyInt(5), MyInt(10))) // true
}
5. 约束组合
约束可以组合使用:
type ComparableStringer interface {
comparable
String() string
}
func Process[T ComparableStringer](a, b T) {
if a == b {
fmt.Println(a.String(), "equals", b.String())
}
}
Go的类型约束系统通过接口定义,支持类型集合、方法集和近似匹配,提供了灵活的类型参数约束机制。