Type parameters
Type parameters for Go functions give you the ability to parameterize a function with types that support generic input. It’s a way to specify to the compiler the types allowed when invoking a generic function and represents a placeholder for a type within a given function. Type parameter lists look like normal parameter lists but are encompassed by square brackets. For example, [T any]
declares a T
type parameter that can be any type. The any
keyword was touched on in the previous chapter.
To continue to understand type parameters, let’s return to our maximum generic function signature from the earlier example code:
func findMaxGeneric[Num int | float64](nums []Num) Num {
This indicates that our function, titled findMaxGeneric
, includes a type parameter, Num
, that can be instantiated by an integer or float64 type. It will take in a slice of Num
and return the resulting maximum integer or float64 value.
An interesting concept associated with...