Golang泛型的使用

package main

import (
	"fmt"
)

/**
泛型的使用,泛型方法不允许暴露(泛型只能在同一个包中使用,所以要注意大小写),感觉没有什么卵用
*/

//泛型方法定义
func gpTe[T any](i T) T {
	return i
}

//泛型结构体定义
type my[T any] struct {
	Name T
}

//泛型切片
type myc[T any] []T

//*泛型Map,这里需要注意,定义泛型Map时需要为Key设置类型约束
//先定义了一个约束
//使用interface进行约束
type MyType interface{
type string, int, bool
}

//之后定义了一个泛型Map
type myMap[K MyType, V any] map[K]V

// *使用func进行约束。泛型约束为 实现了getValue()函数的结构体
type Mytype2 interface {
	getValue() string
}

// tt实现了getValue()方法,所以Mytype2 对应的地方可以使用tt
type tt struct {
	Name string
}

//如果为*tt则会报错
func (t tt) getValue() string {
	return t.Name
}

//之后定义了一个泛型方法。上面的Mytype2约束了gpFunc方法
func gpFunc[T Mytype2](t T) {
	fmt.Println(t.getValue())
}

//也可以将两种约束混用(type+接口的混合使用)。既要满足string, int, bool其中之一,也要满足实现了getValue() string方法
type myType3 interface{
type string, int, bool
getValue() string
}

//为struct绑定的泛型方法
type mytstruct[T any] struct {
	Name string
}

func (m mytstruct[T]) gpSF(t T) T {
	return t
}

func main() {
	//需要在Go Tool Arguments中增加:-gcflags=-G=3,否则会报错
	fmt.Println(gpTe[string]("123") + "456")

	my := my[string]{
		Name: "qin",
	}
	fmt.Println(my)

	//这里不要写成:i := []myc[string]{"这是一个泛型切片"}
	i := myc[string]{"这是一个泛型切片"}
	fmt.Println(i)

	c := make(myMap[string, int])
	c["test"] = 1
	fmt.Println(c)

	temp := tt{"test2"}
	gpFunc[tt](temp)

	mystruct := mytstruct[string]{"为struct绑定的泛型方法"}
	fmt.Println(mystruct.gpSF("测试成功"))
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值