Generic function declarations
August 22, 2023
Function declarations
…
If the function declaration specifies type parameters, the function name denotes a generic function. A generic function must be instantiated before it can be called or used as a value.
func min[T ~int|~float64](x, y T) T { if x < y { return x } return y }
We’ve mentioned instantiation before, but it will be covered in depth later. For now, it’s enough to show an example of what the spec means can’t be done without instantiating a generic function:
func notGeneric(a int) int { /* ... */ }
func generic[T int|float64](a T) T { /* ... */ }
var x = notGeneric // valid, x is of type func(int) int
var y = generic // invalid, until the function is instantiated, T's type is unknown, thus the function's type is undetermined
var z = generic[int] // valid, z is of type func(int) int
Quotes from The Go Programming Language Specification Version of August 2, 2023