wx

关注公众号

Go 编程语言之旅

5、泛型

Go支持使用类型参数进行泛型编程。本课展示了在代码中使用泛型的一些示例。

类型参数

Go函数可以使用类型参数让函数支持多个类型。函数的类型参数用中括号包裹,位于函数的参数之前。

func Index[T comparable](s []T, x T) int

这个声明意味着s是任何类型T的一个切片,它满足comparable内置约束。x也是相同类型的值。 compatible是一个有用的约束,可以使用==和!=类型值上的运算符。在本例中,我们使用它将一个值与所有切片元素进行比较,直到找到匹配。此Index函数适用于任何支持比较的类型。

package main

import "fmt"

// Index returns the index of x in s, or -1 if not found.
func Index[T comparable](s []T, x T) int {
	for i, v := range s {
		// v and x are type T, which has the comparable
		// constraint, so we can use == here.
		if v == x {
			return i
		}
	}
	return -1
}

func main() {
	// Index works on a slice of ints
	si := []int{10, 20, 15, -10}
	fmt.Println(Index(si, 15))

	// Index also works on a slice of strings
	ss := []string{"foo", "bar", "baz"}
	fmt.Println(Index(ss, "hello"))
}

泛型类型

除了泛型函数外,Go还支持泛型类型。可以使用类型参数对类型进行参数化,这对于实现泛型数据结构非常有用。

package main

// List represents a singly-linked list that holds
// values of any type.
type List[T any] struct {
	next *List[T]
	val  T
}

func main() {
}

此示例演示了一个简单的类型声明,用于包含任何类型值的单链列表。

🛒 站长推荐(京东联盟)

以上链接含京东联盟推广代码;通过链接购买本站可能获得少量佣金,不影响你的购买价格。

📮 关注公众号「Go2AI之路」
Go2AI之路 公众号二维码

每周更新 Go + AI 应用开发实战:AI 面试官完整项目、MCP、Agent 工程化,完整源码随文章首发。

微信扫码,或搜索「Go2AI之路」关注,第一时间获取系列更新与源码,不再错过任何一篇。

如有疑问关注公众号给我留言
wx

关注公众号

©2017-2026 鲁ICP备17023316号-1 Powered by Hugo · 隐私政策