Go Variadic Functions
Functions that accept variable number of arguments
🔢 What are Variadic Functions?
Variadic functions accept a variable number of arguments of the same type. Use three dots (...) before the type to create flexible functions that work with any number of parameters.
// Variadic function that sums numbers
func sum(numbers ...int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
func main() {
result := sum(1, 2, 3, 4, 5)
fmt.Println("Sum:", result)
}
Output:
Sum: 15
Key Variadic Concepts
Syntax
Use ... before type for variadic parameter
func myFunc(args ...int) {
// args is a slice
}
Flexibility
Accept zero or more arguments
myFunc() // 0 args
myFunc(1, 2, 3) // 3 args
Slice Access
Variadic parameters become slices
for _, arg := range args {
// Process each argument
}
Spreading
Pass slice as variadic arguments
nums := []int{1, 2, 3}
myFunc(nums...) // Spread slice
🔹 Basic Variadic Functions
Create functions that accept variable number of arguments:
package main
import "fmt"
// Variadic function to find maximum
func findMax(numbers ...int) int {
if len(numbers) == 0 {
return 0
}
max := numbers[0]
for _, num := range numbers {
if num > max {
max = num
}
}
return max
}
// Variadic function to concatenate strings
func joinStrings(separator string, words ...string) string {
result := ""
for i, word := range words {
if i > 0 {
result += separator
}
result += word
}
return result
}
func main() {
// Call with different number of arguments
max1 := findMax(5, 2, 8, 1, 9)
max2 := findMax(10, 20)
max3 := findMax() // No arguments
fmt.Println("Max 1:", max1)
fmt.Println("Max 2:", max2)
fmt.Println("Max 3:", max3)
// String joining
sentence := joinStrings(" ", "Hello", "World", "from", "Go")
fmt.Println("Sentence:", sentence)
}
Output:
Max 1: 9
Max 2: 20
Max 3: 0
Sentence: Hello World from Go
🔹 Spreading Slices
Pass slices to variadic functions using the spread operator:
package main
import "fmt"
func sum(numbers ...int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
func average(numbers ...float64) float64 {
if len(numbers) == 0 {
return 0
}
total := 0.0
for _, num := range numbers {
total += num
}
return total / float64(len(numbers))
}
func main() {
// Direct arguments
sum1 := sum(1, 2, 3, 4)
fmt.Println("Sum 1:", sum1)
// Using slice with spread operator
numbers := []int{5, 6, 7, 8}
sum2 := sum(numbers...) // Spread the slice
fmt.Println("Sum 2:", sum2)
// Float example
scores := []float64{85.5, 92.0, 78.5, 96.0}
avg := average(scores...)
fmt.Printf("Average: %.2f\n", avg)
}
Output:
Sum 1: 10
Sum 2: 26
Average: 88.00
🔹 Mixed Parameters
Combine regular parameters with variadic parameters:
package main
import "fmt"
// Regular parameter + variadic parameter
func greetAll(greeting string, names ...string) {
for _, name := range names {
fmt.Printf("%s, %s!\n", greeting, name)
}
}
// Multiple regular parameters + variadic
func calculateTotal(tax float64, discount float64, prices ...float64) float64 {
subtotal := 0.0
for _, price := range prices {
subtotal += price
}
// Apply discount
subtotal = subtotal * (1 - discount)
// Add tax
total := subtotal * (1 + tax)
return total
}
func main() {
// Greeting example
greetAll("Hello", "Alice", "Bob", "Charlie")
fmt.Println("---")
// Calculation example (10% tax, 5% discount)
total := calculateTotal(0.10, 0.05, 100.0, 50.0, 25.0)
fmt.Printf("Total: $%.2f\n", total)
}
Output:
Hello, Alice!
Hello, Bob!
Hello, Charlie!
---
Total: $183.25