![]() |
VOOZH | about |
Variadic functions in Go allow you to pass a variable number of arguments to a function. This feature is useful when you don’t know beforehand how many arguments you will pass. A variadic function accepts multiple arguments of the same type and can be called with any number of arguments, including none.
Sum of 1, 2, 3: 6 Sum of 4, 5: 9 Sum of no numbers: 0
func functionName(parameters ...Type) ReturnType {
// Code
}
In the syntax above:
parameters ...Type indicates that the function can accept a variable number of arguments of type Type.Table of Content
When defining a variadic function, you specify the type of the arguments followed by an ellipsis (...) as shown in the above example. Inside the function, these arguments can be treated as a slice.
You can call a variadic function with any number of arguments, including zero. The function treats the arguments as a slice.
Sum of 1, 2, 3: 6 Sum of 4, 5: 9 Sum of no numbers: 0
You can also mix variadic parameters with regular parameters in a function. The variadic parameter must always be the last parameter.
Sum of numbers: Number: 1 Number: 2 Number: 3 Another sum: Number: 4 Number: 5 No numbers sum: