Golang中有多少种类型约束

Golang中有多少种类型约束 论坛大家好,

类型参数可以有多少种类型约束?我阅读了一些文档,知道了这两种:comparableany。我觉得这非常有限。有没有一个完整的列表可以供我查阅?

如何使用类型参数编写一个小于函数?

谢谢

func Equal[T comparable](a, b T) bool {
	return a == b
}

//return true if a < b
// func Less(a, b) bool {
//}
3 回复

谢谢 Jeff,

这非常有帮助。

更多关于Golang中有多少种类型约束的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


关于用户定义类型约束的教程,请参阅 Tutorial: Getting started with generics - The Go Programming Language

更详细的阐述,请参阅 Generics in Go — Bitfield Consulting

在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的类型约束系统通过接口定义,支持类型集合、方法集和近似匹配,提供了灵活的类型参数约束机制。

回到顶部