Variadic Functions
Introduction to Variadic Functions
Variadic functions in Go allow you to pass a variable number of arguments to a function. They provide flexibility in function design and are particularly useful when you don't know the exact number of arguments in advance.
Basic Syntax
func sum(numbers ...int) int {
total := 0
for _, number := range numbers {
total += number
}
return total
}
func main() {
result1 := sum(1, 2, 3)
result2 := sum(10, 20, 30, 40)
fmt.Println(result1, result2)
}
Variadic Function Characteristics
Feature |
Description |
Example |
Ellipsis (...) |
Indicates variable arguments |
func(args ...type) |
Slice Conversion |
Arguments converted to slice |
numbers []int |
Flexible Argument Count |
Can pass zero or multiple arguments |
sum() , sum(1,2,3) |
Argument Passing Mechanism
graph LR
A[Variadic Function Call] --> B[Arguments Collected]
B --> C[Converted to Slice]
C --> D[Function Execution]
Advanced Variadic Function Techniques
Mixing Fixed and Variadic Parameters
func printInfo(prefix string, values ...int) {
fmt.Print(prefix + ": ")
for _, v := range values {
fmt.Print(v, " ")
}
fmt.Println()
}
func main() {
printInfo("Numbers", 1, 2, 3, 4)
}
Slice Unpacking
numbers := []int{1, 2, 3}
result := sum(numbers...) // Unpack slice
Use Cases for LabEx Developers
- Logging functions
- Aggregation operations
- Flexible configuration methods
- Dynamic argument processing
- Variadic functions create a slice for arguments
- Overhead is minimal for small argument lists
- For large argument lists, consider alternative approaches
Error Handling and Validation
func validatePositive(numbers ...int) error {
for _, num := range numbers {
if num < 0 {
return fmt.Errorf("negative number found: %d", num)
}
}
return nil
}
Variadic functions provide a powerful way to create flexible and dynamic functions in Go, allowing developers to write more adaptable and concise code.