首页 > 文章列表 > 泛型在golang中的特殊用例和技巧

泛型在golang中的特殊用例和技巧

golang 泛型
225 2024-05-05

Go 中泛型的特殊用例和技巧使用空类型接口进行动态类型检查,检查运行时类型。在集合中使用泛型类型参数,创建多样化类型的容器。实现泛型方法,为不同类型的参数执行通用操作。使用类型约束实现特定类型泛型,为指定类型定制操作。

泛型在golang中的特殊用例和技巧

泛型在 Go 中的特殊用例和技巧

泛型引入了新颖的功能,使得编写灵活高效的代码成为可能。本文将探讨 Go 中泛型的特殊用例和技巧。

1. 使用空类型接口进行动态类型检查

any 类型可以表示任何类型。这使得我们能够根据运行时确定的类型执行动态类型检查。

func isString(v any) bool {
    _, ok := v.(string)
    return ok
}

func main() {
    x := "hello"
    y := 10
    fmt.Println(isString(x)) // true
    fmt.Println(isString(y)) // false
}

2. 在集合上使用泛型类型

泛型类型参数可以在集合类型中使用,从而创建一个多样化类型的容器。

type Stack[T any] []T

func (s *Stack[T]) Push(v T) {
    *s = append(*s, v)
}

func (s *Stack[T]) Pop() T {
    if s.IsEmpty() {
        panic("stack is empty")
    }

    v := (*s)[len(*s)-1]
    *s = (*s)[:len(*s)-1]
    return v
}

func main() {
    s := new(Stack[int])
    s.Push(10)
    s.Push(20)
    fmt.Println(s.Pop()) // 20
    fmt.Println(s.Pop()) // 10
}

3. 实现泛型方法

泛型方法允许我们为不同类型的参数实现通用操作。

type Num[T numeric] struct {
    V T
}

func (n *Num[T]) Add(other *Num[T]) {
    n.V += other.V
}

func main() {
    n1 := Num[int]{V: 10}
    n2 := Num[int]{V: 20}
    n1.Add(&n2)
    fmt.Println(n1.V) // 30

    // 可以使用其他数字类型
    n3 := Num[float64]{V: 3.14}
    n4 := Num[float64]{V: 2.71}
    n3.Add(&n4)
    fmt.Println(n3.V) // 5.85
}

4. 使用类型约束实现特定类型泛型

类型约束限制泛型类型的范围。它允许我们为特定类型实现定制操作。

type Comparer[T comparable] interface {
    CompareTo(T) int
}

type IntComparer struct {
    V int
}

func (c *IntComparer) CompareTo(other IntComparer) int {
    return c.V - other.V
}

// IntSlice 实现 Comparer[IntComparer] 接口
type IntSlice []IntComparer

func (s IntSlice) Len() int {
    return len(s)
}

func (s IntSlice) Less(i, j int) bool {
    return s[i].CompareTo(s[j]) < 0
}

func (s IntSlice) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}

func main() {
    s := IntSlice{{10}, {20}, {5}}
    sort.Sort(s)
    fmt.Println(s) // [{5} {10} {20}]
}

这些特殊用例和技巧展示了泛型在 Go 中的强大功能,它允许创建更通用、灵活和高效的代码。