go语言中的泛型T

泛型

Golang在1.18版本(2022年3月发布)引入泛型特性。
Go泛型解决了函数、方法、结构体和接口的复用性问题,
并在编译时提供对不特定数据类型的类型安全支持。

泛型的产生

package main
import (
	"fmt"
)
func getString(value string) string {
	return value
}
func getInt(value int) int {
	return value
}
func getBoolData(value bool) bool {
	return value
}
func main() {
	str := getString("hello world")
	fmt.Println(str) // hello world
	int := getInt(100)
	fmt.Println(int) // 100
	bool := getBoolData(true)
	fmt.Println(bool) // true
}

通过上面的代码,我们发现实现的功能是:
根据传入不同的数据类型,然后返回不同的值。
我们没有必要写3个不同的函数来实现这个功能。
我们可以实现接口来实现这个功能点

使用接口interface 来实现这个功能点

import (
	"fmt"
)

func getDataInterface(value interface{}) interface{} {
	return value
}
func main() {
	str := getDataInterface("hello world")
	// 这里我们必须使用断言来获取实际的类型,
	// 因为返回来的是一个空接口
	fmt.Println(len(str.(string))) 
}

通过interface{} 来实现这个功能点,
但是interface{} 不会对传入的数据类型进行校验了。
这个时候我们就需要引入泛型了

泛型

使用方括号[]声明类型参数:
[T any]声明了一个类型参数T,any表示T可以是任何类型。
函数可以接受和返回任意类型的值

package main

import (
	"fmt"
)

// T 表示是一个参数,any 表示这个参数T可以是任何类型
func getDataInterface[T any](value T) T {
	return value
}

func main() {
	str := getDataInterface("hello world")
	fmt.Println(len(str)) // 11
}

自定义类型

package main

import (
	"fmt"
)

type MyNumber interface {
	int32 | int64 | float32 | float64
}

// 定义了一个参数T,这个T可以是int32, int64, float32, float64
func Add[T MyNumber](a, b T) T {
	return a + b
}
func main() {
	str := Add(10, 45.3434)
	fmt.Println(str) // 55.3434
}

传递浮点类型报错的问题

package main

import (
	"fmt"
)

type Container struct {
	Value int
}

func (c *Container) SetValue(value int) {
	c.Value = value
}

func (c *Container) GetValue() int {
	return c.Value
}

func main() {
	container := Container{}
	// 这里只能够传递int类型
	container.SetValue(100)
	// ,传递浮点类型的话会报错
	//  container.SetValue(100.1210) 报错
	fmt.Println(container.GetValue()) // 100
}

怎么解决传递浮点类型会报错的问题

package main

import (
	"fmt"
)

type Container[T any] struct {
	Value T
}

func (c *Container[T]) SetValue(value T) {
	c.Value = value
}

func (c *Container[T]) GetValue() T {
	return c.Value
}

func main() {
	container := Container[int]{0}
	// 这里只能够传递int类型
	container.SetValue(100)

	// 这里只能够传递float64类型
	containerFloat := Container[float64]{0.0}
	containerFloat.SetValue(100.1210)
	fmt.Println(containerFloat.GetValue())
}

这样就可以传递任意类型的值了。并且会进行类型校验。

尾声

今天 26.10.17 16:19学习go语言的基础就已经学习完了

posted @ 2026-10-17 16:20  何人陪我共长生  阅读(20)  评论(0)    收藏  举报