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
相关推荐
ttwuai4 天前
Go开源后台管理系统推荐:怎么按技术栈和边界比较4个官方仓库?
golang·gin
codeejun4 天前
每日一Go·MySQL-5、锁机制全解析
云原生·golang
Achou.Wang4 天前
k8s中nginx worker process自动设置
后端·golang
指尖的爷5 天前
ARM 架构 Ubuntu(RK3588/aarch64)go开发环境安装手册
ubuntu·架构·golang
名字还没想好☜5 天前
Go 实现指数退避重试:context 取消、抖动 jitter 与什么时候别重试
后端·golang·go
Casbin开源社区5 天前
OpenAgent 详解:单二进制自托管 AI Agent 平台,30+ 模型接入、RAG 知识库、MCP 工具调用与 Casbin 工具权限
人工智能·golang·开源
五彩小白6 天前
GO语言装饰器语法
golang
金金计较.6 天前
Go语言-4
开发语言·golang
名字还没想好☜7 天前
Go context.AfterFunc 实战(Go 1.21):context 一取消就自动跑清理,告别手写 goroutine 监听 Done
后端·golang·go
web守墓人7 天前
【goed/ui】自定义组件设计思想篇
linux·windows·ui·golang