Go language reference confusion regarding type constraints

Issue

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?

Solution

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 {
    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

Answered By – blackgreen

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.