Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading