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

在 Go Language reference 中,关于Type parameter declarations的部分,我看到[P Constraint[int]]了一个类型参数示例。

这是什么意思?如何在通用函数定义中使用此结构?


萧十郎
浏览 150回答 2
2回答

杨__羊羊

它是一个类型参数列表,如您链接的段落中所定义,它有一个类型参数声明:P作为类型参数名称Constraint[int]作为约束whereasConstraint[int]是泛型的实例化(您必须始终在使用时实例化泛型)。在语言规范的那段中,Constraint没有定义,但它可以合理地成为一个通用接口:

繁星coding

type Constraint[T any] interface {    DoFoo(T)}type MyStruct struct {}// implements Constraint instantiated with intfunc (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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go