在GO语言参考中,在有关作为类型参数示例。
这是什么意思? 如何在通用函数定义中使用此结构?
In the Go Language reference, on the section regarding Type parameter declarations, I see [P Constraint[int]] as a type parameter example.
[P Constraint[int]]
What does it mean? How to use this structure in a generic function definition?
这是您链接的段落中定义的类型参数列表,其中一个类型参数声明具有:
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
Constraint[int]
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:
Constraint
And you can use it as you would use any type parameter constraint:
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?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
暂无简介
文章 0 评论 0
接受
发布评论
评论(1)
这是您链接的段落中定义的类型参数列表,其中一个类型参数声明具有:
p
作为类型参数名称约束[int]
作为约束而
约束[int]
是 instantiation>您必须在使用时始终实例化通用类型)。在该语言规范的那段段落中,
约束
尚未定义,但它可以合理地是一个通用接口:您可以使用它,因为您可以使用任何类型的参数约束:
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 nameConstraint[int]
as the constraintwhereas
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:And you can use it as you would use any type parameter constraint:
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?