为了账号安全,请及时绑定邮箱和手机立即绑定

Go泛型:泛型类型约束的语法

Go泛型:泛型类型约束的语法

Go
萧十郎 2022-12-19 21:35:05
在 Go Language reference 中,关于Type parameter declarations的部分,我看到[P Constraint[int]]了一个类型参数示例。这是什么意思?如何在通用函数定义中使用此结构?
查看完整描述

2 回答

?
杨__羊羊

TA贡献1943条经验 获得超7个赞

它是一个类型参数列表,如您链接的段落中所定义,它有一个类型参数声明:

  • P作为类型参数名称

  • Constraint[int]作为约束

whereasConstraint[int]是泛型的实例化(您必须始终在使用时实例化泛型)。

在语言规范的那段中,Constraint没有定义,但它可以合理地成为一个通用接口:


查看完整回答
反对 回复 2022-12-19
?
繁星coding

TA贡献1797条经验 获得超4个赞

type Constraint[T any] interface {

    DoFoo(T)

}


type MyStruct struct {}


// implements Constraint instantiated with int

func (m MyStruct) DoFoo(v int) { 

    fmt.Println(v)

}

您可以像使用任何类型参数约束一样使用它:


func Foo[P Constraint[int]](p P) {

    p.DoFoo(200)

}


func main() {

    m := MyStruct{} // satisfies Constraint[int]

    Foo(m)

}

游乐场:https ://go.dev/play/p/aBgva62Vyk1


查看完整回答
反对 回复 2022-12-19
  • 2 回答
  • 0 关注
  • 149 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号