GO GENRICS:通用类型约束的语法

发布于 2025-02-07 17:47:43 字数 166 浏览 1 评论 0 原文

在GO语言参考中,在有关作为类型参数示例。

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

预谋 2025-02-14 17:47:43

这是您链接的段落中定义的类型参数列表,其中一个类型参数声明具有:

  • p 作为类型参数名称
  • 约束[int] 作为约束

约束[int] instantiation>您必须在使用时始终实例化通用类型)。

在该语言规范的那段段落中,约束尚未定义,但它可以合理地是一个通用接口:

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)
}

playground: https://go.dev/play/p/abgva62vyk1

这种约束的用法显然是自因:您可以简单地将该实例化接口用作参数类型。

有关有关通用接口实现的更多详细信息,您可以看到:如何实现通用接口?

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

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

For more details about implementation of generic interfaces, you can see: How to implement generic interfaces?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文