fmt.Println being one of the most common examples.
Defining Variadic Functions
Use the... syntax before the parameter type to accept a variable number of arguments:
Within the function, the type of
nums is equivalent to []int (a slice). You can call len(nums), iterate over it with range, and use any other slice operations.Calling Variadic Functions
Variadic functions can be called with any number of arguments:Slice Expansion
If you already have arguments in a slice, you can expand them into a variadic function using...:
nums... syntax unpacks the slice so its elements are passed as individual arguments.
Complete Example
Practical Examples
String Formatting
Logging
Variadic Parameters with Other Parameters
Variadic parameters must be the last parameter in the function signature:Working with Empty Arguments
Variadic functions can be called with zero arguments:Best Practices
Use variadic functions for flexible APIs
Use variadic functions for flexible APIs
Variadic functions are ideal when you want to provide a convenient API that accepts varying numbers of arguments:
Consider performance implications
Consider performance implications
Each call to a variadic function creates a new slice. For performance-critical code, consider accepting a slice directly instead.
Validate input length when necessary
Validate input length when necessary
Check the length of variadic parameters if your function requires a minimum number of arguments:
Key Takeaways
- Variadic functions accept any number of arguments using
...Typesyntax - Inside the function, variadic parameters behave like slices
- Use
slice...to expand a slice into individual arguments - Variadic parameters must be the last parameter in the signature
- You can only have one variadic parameter per function