为什么需要泛型?

Go 1.18 引入了泛型,让我们可以编写类型安全且可复用的代码。

基本语法

func Max[T constraints.Ordered](a, b T) T {
    if a > b {
        return a
    }
    return b
}

自定义泛型类型

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
}

最佳实践

  1. 优先使用接口,只在必要时用泛型
  2. 保持泛型约束尽量宽松
  3. 避免过度抽象