Function types

March 29, 2023

Go has first-class functions. That is to say, functions are treated as any other data type, and can be passed around as arguments, used as struct field types, etc.

Function types

A function type denotes the set of all functions with the same parameter and result types. The value of an uninitialized variable of function type is nil.

FunctionType   = "func" Signature .
Signature      = Parameters [ Result ] .
Result         = Parameters | Type .
Parameters     = "(" [ ParameterList [ "," ] ] ")" .
ParameterList  = ParameterDecl { "," ParameterDecl } .
ParameterDecl  = [ IdentifierList ] [ "..." ] Type .

Notice the definition, though: A function type denotes the set of all functions with the same parameter type and result types. Nothing is said about the names of those parameters and results. This means that the following two functions are of the same type:

func(x int) int
func(y int) int

As are these:

func(r *http.Request) (err error)
func(req *httpRequest) error

The parameter and result names don’t affect the function’s type at all.

Quotes from The Go Programming Language Specification Version of December 15, 2022


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .