Golang 泛型支持的类型

217 阅读2分钟

在 Go 1.18 及以后版本中,泛型支持以下几种类型:

  1. 函数:你可以定义具有泛型参数的函数。
  2. 结构体:你可以定义具有泛型参数的结构体。
  3. 接口:你可以定义具有泛型参数的接口。

1. 泛型函数

你可以定义一个泛型函数,函数的类型参数在函数名称后面声明:

package main

import "fmt"

// 泛型函数,接收一个参数并返回同类型的值
func Print[T any](value T) T {
    fmt.Println(value)
    return value
}

func main() {
    Print(42)          // 输出: 42
    Print("Hello")     // 输出: Hello
}

2. 泛型结构体

你可以定义一个泛型结构体,结构体的类型参数在结构体名称后面声明:

package main

import "fmt"

// 泛型结构体
type Pair[T any, U any] struct {
    First  T
    Second U
}

func main() {
    p := Pair[int, string]{First: 1, Second: "One"}
    fmt.Println(p) // 输出: {1 One}
}

3. 泛型接口

你可以定义一个泛型接口,接口的类型参数在接口名称后面声明:

package main

import "fmt"

// 泛型接口
type Adder[T any] interface {
    Add(a, b T) T
}

// 实现泛型接口的结构体
type IntAdder struct{}

func (IntAdder) Add(a, b int) int {
    return a + b
}

func main() {
    var adder Adder[int] = IntAdder{}
    fmt.Println(adder.Add(1, 2)) // 输出: 3
}

4. 泛型方法

虽然 Go 目前不支持为方法单独定义泛型参数,但你可以通过在结构体或接口上定义泛型参数来实现泛型方法:

package main

import "fmt"

// 定义一个泛型结构体
type Container[T any] struct {
    value T
}

// 定义一个方法,但不带额外的泛型参数
func (c Container[T]) GetValue() T {
    return c.value
}

func main() {
    intContainer := Container[int]{value: 42}
    fmt.Println("Int value:", intContainer.GetValue())

    stringContainer := Container[string]{value: "Hello, Generics!"}
    fmt.Println("String value:", stringContainer.GetValue())
}

在这个示例中,虽然不能直接为方法定义泛型参数,但可以通过在结构体或接口上定义泛型参数来实现泛型方法。

通过这种方式,你可以在 Go 中定义和使用泛型函数、结构体、接口以及方法。