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?
CodePudding user response:
It's a type parameter list, as defined in the paragraph you linked, with:
P
as the type parameter nameConstraint[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?