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

See this in the playground

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

Share this

Related Content

Generic functions as operands

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:

Empty function declarations

Function declarations … A function declaration without type parameters may omit the body. Such a declaration provides the signature for a function implemented outside Go, such as an assembly routine. func flushICache(begin, end uintptr) // implemented externally This is something I have never used. Most developers probably never will. Although I’ve certainly seen it a few times, particularly while browsing the standard library source code, so it’s good to be aware of it, so you aren’t stuck scratching your head when you see it.

Function declarations

No livestream today. My family is on vacation this week. I’ll be livestreaming again next week! Function declarations A function declaration binds an identifier, the function name, to a function. FunctionDecl = "func" FunctionName [ TypeParameters ] Signature [ FunctionBody ] . FunctionName = identifier . FunctionBody = Block . Nothing surprising here… So let’s move on to the first interesting rule: If the function’s signature declares result parameters, the function body’s statement list must end in a terminating statement.