Functions
Go Variadic Functions
Variadic Functions
Go variadic functions use ... for variable argument lists.
Introduction to Variadic Functions in Go
In Go, variadic functions allow you to pass a variable number of arguments of the same type to a function. This is particularly useful when you don't know beforehand how many arguments will be passed. Variadic functions are defined by using an ellipsis (...
) before the parameter type.
Syntax of Variadic Functions
To declare a variadic function, place an ellipsis (...
) before the parameter type. This indicates that the function can accept zero or more arguments of that type. For example, you can declare a function that sums an arbitrary number of integers.
In the above example, the sum
function takes a variadic parameter of type int
. Inside the function, numbers
is treated as a slice of integers.
Calling a Variadic Function
When calling a variadic function, you can pass individual arguments, or you can pass a slice of the same type using the ellipsis syntax (...
), which is known as "unpacking" the slice.
In the main
function, we demonstrate both ways of calling the sum
function. First, by passing individual integers, and then by passing a slice of integers using the ellipsis (nums...
) to unpack it.
Mixing Variadic and Regular Parameters
A variadic parameter must be the last parameter in a function's parameter list. You can still have regular parameters before it. For example:
In this greet
function, prefix
is a regular string parameter, while names
is a variadic parameter. You can pass one or more names to be greeted.
Conclusion and Best Practices
Variadic functions in Go provide flexibility when the number of function arguments is not fixed. It's important to remember that only the last parameter can be variadic, and you can use slices to pass multiple arguments easily. Use variadic functions judiciously to keep your code clean and readable.
Functions
- Functions
- Multiple Returns
- Named Returns
- Anonymous Functions
- Variadic Functions
- Closures
- Recursion
- Function Types
- Previous
- Anonymous Functions
- Next
- Closures