Variadic Functions
Go's variadic functions let you define functions that accept any number of arguments. By placing ... before the type of the last parameter, the function receives zero or more values as a slice.
Syntax
// Variadic function definition (only the last parameter can be variadic).
func funcName(fixed type, args ...type) {
// args is treated as a slice.
for _, v := range args {
// Process each element.
}
}
// Calling with individual values.
funcName(fixed, value1, value2, value3)
// Expanding a slice and passing it (append ... after the slice).
slice := []int{1, 2, 3}
funcName(fixed, slice...)
Characteristics of Variadic Functions
| Feature | Description |
|---|---|
| Last parameter only | The variadic parameter must be the last parameter in the function signature. |
| Received as a slice | Inside the function, the variadic arguments are treated as a slice (nil if no arguments are passed). |
| Slice expansion | To pass an existing slice, write slice... to expand it. |
| Zero arguments allowed | Passing no arguments does not cause an error. |
Sample Code
package main
import "fmt"
// Variadic function that returns the sum of integers.
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// Combines a fixed parameter with variadic parameters.
func logMessage(level string, messages ...string) {
for _, msg := range messages {
fmt.Printf("[%s] %s\n", level, msg)
}
}
// Passes variadic arguments to another variadic function.
func printAll(args ...interface{}) {
fmt.Println(args...) // fmt.Println itself is also variadic.
}
func main() {
// Passing values directly.
fmt.Println("Sum (no args):", sum())
fmt.Println("Sum (one arg):", sum(5))
fmt.Println("Sum (multiple):", sum(1, 2, 3, 4, 5))
fmt.Println()
// Expanding a slice and passing it.
nums := []int{10, 20, 30}
fmt.Println("From slice:", sum(nums...))
fmt.Println()
// Combining fixed and variadic parameters.
logMessage("INFO", "Server started", "Listening on port 8080")
logMessage("WARN") // Works even with no messages.
fmt.Println()
// Variadic with interface{}.
printAll("Go", 42, true, 3.14)
}
Notes
Variadic functions are used throughout the standard library — fmt.Println() and fmt.Printf() both use variadic parameters internally. To forward variadic arguments to another variadic function, you must expand them with args....
If you call a variadic function with no arguments, the slice inside the function will be nil. Because len() returns 0, this is usually fine, but it is safer to perform a nil check before any slice operations such as index access.
For the basics of functions, see 'Function Definition / Multiple Return Values'. For closures, see 'Closures / Anonymous Functions'.
If you find any errors or copyright issues, please contact us.