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

huangapple go评论152阅读模式
英文:

Go generics: syntax of generic type constraints

问题

在Go语言参考中,关于类型参数声明的部分,我看到[P Constraint[int]]作为一个类型参数的示例。

这是什么意思?
如何在泛型函数定义中使用这个结构?

英文:

In the Go Language reference, on the section regarding Type parameter declarations, I see [P Constraint[int]] as a type parameter example.

What does it mean?
How to use this structure in a generic function definition?

答案1

得分: 4

这是一个类型参数列表,如你所链接的段落中所定义的,它有一个类型参数声明,具有以下内容:

  • P 作为类型参数名称
  • Constraint[int] 作为约束条件

Constraint[int] 是一个泛型类型的实例化(在使用时必须始终实例化泛型类型)。

在语言规范的那个段落中,Constraint 没有被定义,但它可以合理地是一个泛型接口:

type Constraint[T any] interface {
    DoFoo(T)
}

type MyStruct struct {}

// 实现了以 int 实例化的 Constraint
func (m MyStruct) DoFoo(v int) { 
    fmt.Println(v)
}

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

func Foo[P Constraint[int]](p P) {
    p.DoFoo(200)
}

func main() {
    m := MyStruct{} // 满足 Constraint[int]
    Foo(m)
}

Playground: https://go.dev/play/p/aBgva62Vyk1

显然,这个约束的使用是人为的:你可以简单地将实例化的接口作为参数的类型使用。

关于实现泛型接口的更多细节,你可以参考:https://stackoverflow.com/questions/72034479/how-to-implement-generic-interfaces/72050933#72050933

英文:

It's a type parameter list, as defined in the paragraph you linked, that has one type parameter declaration that has:

  • P as the type parameter name
  • Constraint[int] as the constraint

whereas Constraint[int] is an instantiation of a generic type (you must always instantiate generic types upon usage).

In that paragraph of the language spec, Constraint isn't defined, but it could reasonably be a generic interface:

type Constraint[T any] interface {
    DoFoo(T)
}

type MyStruct struct {}

// implements Constraint instantiated with int
func (m MyStruct) DoFoo(v int) { 
    fmt.Println(v)
}

And you can use it as you would use any type parameter constraint:

func Foo[P Constraint[int]](p P) {
    p.DoFoo(200)
}

func main() {
    m := MyStruct{} // satisfies Constraint[int]
    Foo(m)
}

Playground: https://go.dev/play/p/aBgva62Vyk1

<sup>The usage of this constraint is obviously contrived: you could simply use that instantiated interface as type of the argument.</sup>

For more details about implementation of generic interfaces, you can see: https://stackoverflow.com/questions/72034479/how-to-implement-generic-interfaces/72050933#72050933

huangapple
  • 本文由 发表于 2022年6月15日 18:42:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/72629965.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定