Go泛型编程实战从类型约束到泛型数据结构

Go泛型编程实战从类型约束到泛型数据结构的完整指南

文章导语

Go 1.18引入了期待已久的泛型。两年多来,泛型已从"新特性"变为日常开发的标配。本文从类型约束到泛型数据结构,覆盖泛型在实际项目中的核心应用。

一、类型约束定义

go 复制代码
// 内置约束
func Max[T constraints.Ordered](a, b T) T {
    if a > b { return a }
    return b
}

// 自定义约束
type Number interface {
    ~int | ~int32 | ~int64 | ~float32 | ~float64
}

func Sum[T Number](nums []T) T {
    var total T
    for _, n := range nums {
        total += n
    }
    return total
}

二、泛型数据结构

go 复制代码
// 泛型Stack
type Stack[T any] struct {
    items []T
}

func (s *Stack[T]) Push(item T) { s.items = append(s.items, item) }
func (s *Stack[T]) Pop() (T, bool) {
    if len(s.items) == 0 {
        var zero T
        return zero, false
    }
    item := s.items[len(s.items)-1]
    s.items = s.items[:len(s.items)-1]
    return item, true
}

// 泛型Set
type Set[T comparable] map[T]struct{}

func NewSet[T comparable]() Set[T] { return make(Set[T]) }
func (s Set[T]) Add(item T)        { s[item] = struct{}{} }
func (s Set[T]) Contains(item T) bool { _, ok := s[item]; return ok }

三、实战:泛型Repository

go 复制代码
type Repository[T any, ID comparable] interface {
    FindByID(id ID) (T, error)
    Save(entity T) error
    Delete(id ID) error
}

四、全文总结

  1. 类型约束定义泛型参数的行为边界
  2. ~T匹配底层类型为T的所有命名类型
  3. 泛型数据结构减少类型转换代码
  4. 避免过度抽象:只在确实需要多类型支持时用泛型

参考文献

  1. Go Blog - An Introduction To Generics
  2. Go泛型设计提案
  3. Go 1.18 Release Notes
相关推荐
codeejun1 小时前
每日一Go·MySQL-22、幻读、不可重复读、脏读实战演示
开发语言·mysql·golang
码途行者9 小时前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
利威尔xu20 小时前
2026-11-24-Go限流器实战
后端·golang
码途行者1 天前
每天10分钟学Go:第21课 错误
开发语言·后端·golang
码途行者1 天前
每天10分钟学Go:第22课 自定义错误
开发语言·后端·golang
码途行者2 天前
每天10分钟学Go:第20课 泛型
c++·算法·golang
codeejun2 天前
每日一Go·MySQL-20、SQL 性能调优实战总结
sql·mysql·golang
利威尔xu3 天前
Go sync.Map底层3层缓存:并发写map直接崩溃,读多写少无锁读拖垮选错锁
golang
利威尔xu4 天前
2026-11-19-Go反射为什么慢面试
开发语言·面试·golang
关键词安全4 天前
PHP / Node.js / Go / Rust 全部中招(CVE-2026-109618、109619、111497、111943)完整排查与修复清单
golang·rust·node.js