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.Printf
in the standard library. This is a function of the following type:
func(string, ...any) (int, error)
That second parameter is variadic. As you may have noticed by using the function, it takes any number of arguments after the format string:
fmt.Printf("foo") // Zero additional arguments
fmt.Printf("Hello, %s!", name) // One additional argument
fmt.Printf("%d. %s\n", index, description) // Or more...
We’ll learn how to use variadic parameters within a function later on in the spec. For now, let’s round out our discussion of function types with the examples provided in the spec:
func() func(x int) int func(a, _ int, z float32) bool func(a, b int, z float32) (bool) func(prefix string, values ...int) func(a, b int, z float64, opt ...interface{}) (success bool) func(int, int, float64) (float64, *[]int) func(n int) func(p *T)
Quotes from The Go Programming Language Specification Version of December 15, 2022