April 3, 2023
Parameter and result lists are always parenthesized except that if there is exactly one unnamed result it may be written as an unparenthesized type.
But more directly: Function parameters must always be wrapped in parenthesis. Function reults must be wrapped in parenthesis if there is more than one result, or if the result is named. Further, though not clear from this wording in the spec, if there are no results, no parenthesis are required, even though if there are no parameters, they are still required.
Let’s look at examples.
func() // No parameters, and no results. The (empty) parameter list must still be parenthesized. func() error // A single, un-named result requires no parentheses. func() (err error) // Parentheses required because the result is named func() (int, error) // Parentheses required because of multiple return values
There may be a few times when you don’t see parentheses that could surprise you, because they appear to violate this rule because they contain multiple words. But keep in mind that some some types are expressed using multiple words.
// This function returns a value of type `func() error` func () func() error // This function returns a value of type `chan bool` func() chan bool
Quotes from The Go Programming Language Specification Version of December 15, 2022
Naming function parameters and results
Function types … Within a list of parameters or results, the names (IdentifierList) must either all be present or all be absent. If present, each name stands for one item (parameter or result) of the specified type and all non-blank names in the signature must be unique. There are several things to unpack here. Let’s start with the most intuitive part: The names of function parameters and results must be unique.
Generally speaking, Go doesn’t allow for the use of optional function parameters. But there is one exception, and that’s where variadic functions come into play. Function types The final incoming parameter in a function signature may have a type prefixed with .... A function with such a parameter is called variadic and may be invoked with zero or more arguments for that parameter. Probably the most ubiquitous example of a variadic function would be fmt.
Collapsing like function parameters
Yesterday we learned that we may omit function parameter and result names in a function type definition. But this poses a small limitation: Function types … If [the name is] absent, each type stands for one item of that type. What does that mean, exactly? Well, when using named parameters and results, we have the option to omit the type for subesquent arguments of the same type. Here’s an example to make it more clear;
Improve your knowledge of Go