首页 > 文章列表 > 泛型函数在Golang中如何与现有的非泛型函数交互?

泛型函数在Golang中如何与现有的非泛型函数交互?

函数 泛型
187 2024-04-23

在 Go 中,泛型函数可以通过使用类型断言、类型别名或空的接口与非泛型代码交互。类型断言允许将值转换为特定类型;类型别名可以创建现有类型的泛型别名;空的接口可以表示任何类型的变量。通过这些方法,泛型函数可以接受或返回非泛型类型的值,从而实现跨不同类型的数据处理。

泛型函数在Golang中如何与现有的非泛型函数交互?

如何在 Go 中让泛型函数与非泛型函数交互

Go 自 Go 1.18 起引入了泛型,为重用类型和算法代码打开了大门。但是,新的泛型代码如何与现有的、非泛型的代码交互呢?

使用类型断言

类型断言提供了一种将一个接口转换为特定类型的值的方法。这可以通过使用 switch 语句完成:

func AnyToString(any interface{}) string {
    switch myString := any.(type) {
    case string:
        return myString
    default:
        return "Unknown"
    }
}

此函数尝试将任意值转换为字符串,如果不是字符串,则返回 "Unknown"。

使用类型别名

类型别名可以创建现有类型的别名。这允许我们为非泛型类型创建泛型别名:

type MyString string

func GenericFunc[T MyString](t T) {}

现在,我们可以使用非泛型类型 MyString 在泛型函数 GenericFunc 中:

GenericFunc(MyString("Hello"))

使用空的接口

空的接口可以表示任何类型的变量。这允许我们创建接受或返回任何类型值的泛型函数:

func GenericEmptyInterfaceFunc(empty interface{}) {}

我们可以使用任何类型的值调用此函数:

GenericEmptyInterfaceFunc(10)
GenericEmptyInterfaceFunc("Hello")

实战案例:实现泛型排序

让我们通过对列表进行排序来演示泛型代码与非泛型代码的交互。

// Sort is a generic function that sorts a slice of any type that implements sort.Interface.
func Sort[T sort.Interface](s []T) {
    sort.Sort(s)
}

// IntSlice implements sort.Interface for a slice of int.
type IntSlice []int

func (s IntSlice) Len() int { return len(s) }
func (s IntSlice) Less(i, j int) bool { return s[i] < s[j] }
func (s IntSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

// StringSlice implements sort.Interface for a slice of string.
type StringSlice []string

func (s StringSlice) Len() int { return len(s) }
func (s StringSlice) Less(i, j int) bool { return s[i] < s[j] }
func (s StringSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func main() {
    intSlice := IntSlice{10, 5, 7, 3, 11}
    Sort(intSlice)
    fmt.Println(intSlice) // Output: [3 5 7 10 11]

    stringSlice := StringSlice{"Hello", "World", "Go", "Golang"}
    Sort(stringSlice)
    fmt.Println(stringSlice) // Output: [Go Golang Hello World]
}

此代码演示了如何使用泛型函数 Sort 根据自定义类型对不同的值列表进行排序。