DEV Community

Huseyn
Huseyn

Posted on

Variadic Function in Go

What is a Variadic Function in Go?
A variadic function is a function that accepts a variable number of arguments of the same type.

This is useful when you don’t know how many values a caller might pass. Instead of defining a fixed number of parameters, you allow the caller to pass zero or more arguments.

Syntax

func myFunc(args ...int) { // args is a slice of int } 
Enter fullscreen mode Exit fullscreen mode
  • The ... before the type means the function accepts any number of int arguments, including none.
  • Inside the function, args behaves like a slice ([]int).

Real-World Example: Sum of Prices
Imagine you’re summing prices of products in a cart:

package main import "fmt" // Variadic function to sum prices func SumPrices(prices ...float64) float64 { total := 0.0 for _, price := range prices { total += price } return total } func main() { fmt.Println(SumPrices(10.99, 20.00)) // 30.99 fmt.Println(SumPrices(5.99, 15.50, 9.99, 1.99)) // 33.47 fmt.Println(SumPrices()) // 0.0 } 
Enter fullscreen mode Exit fullscreen mode

Key Points

Feature Explanation
...type Used only in the last parameter of the function.
Internally Treated as a slice (e.g., []int, []string).
Optional Can pass zero or more values.
Expand slice Use myFunc(mySlice...) to expand a slice into arguments.

Gotchas

func printNames(names ...string) { for _, name := range names { fmt.Println(name) } } func main() { myNames := []string{"Alice", "Bob", "Carol"} // You must use ... to expand a slice printNames(myNames...) // ✅ // printNames(myNames) // ❌ compile error } 
Enter fullscreen mode Exit fullscreen mode

When to Use Variadic Functions

  • Calculations (sum, average)
  • Logging utilities
  • Formatting strings
  • Joining or filtering collections

Top comments (0)