Generic functions as operands

September 12, 2023

Operands

An operand name denoting a generic function may be followed by a list of type arguments; the resulting operand is an instantiated function.

So first off, recall that an operand may be a function literal:

var x = func() { /* ... */ }

Or a variable that represents a function:

var F = func() { /* ... */ }
var f = F // <--- `F` is a variable that represents a function

Or another expression that evaluates to a function:

func X() func() { // X() returns a function
	return func() { /* ... */ }
}

var x = X() // `x` now represents the function returned by X()

The above sentence expands on this simple concept, to allow the instantiation of generic functions. This is required because a function variable or operand cannot be generic. It must be instantiated.

func First[A int | uint](args ...A) A {
	return args[0]
}

var f = First // cannot use generic function First without instantiation

var g = First[int] // Valid, g is of type func(...int) int

Quotes from The Go Programming Language Specification Version of August 2, 2023

Share this