Go language reference confusion regarding type constraints


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?


It’s a type parameter list, as defined in the paragraph you linked, with:

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

whereas Constraint[int] is an instantiation of a generic type.

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

type Constraint[T any] interface {

type MyStruct struct {}

// implements Constraint instantiated with int
func (m MyStruct) DoFoo(v int) { 

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

func Foo[P Constraint[int]](p P) {

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

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

Answered By – blackgreen

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.