# Go by Example: Variadic Functions

In Go, you can define a function that takes a variable number of arguments. These are called variadic functions.

To declare a variadic function, you add an ellipsis `...` before the type of the last parameter in the function signature. This tells Go that the function can take any number of arguments of that type.

Here’s an example of a variadic function that adds up a list of integers:

``````package main

import "fmt"

func sum(numbers ...int) int {
result := 0
for _, num := range numbers {
result += num
}
return result
}

func main() {
fmt.Println(sum(1, 2, 3, 4, 5))
}``````

Output:

``15``

In this example, the `sum` function takes a variable number of `int` arguments. The function uses a `for` loop to iterate over the `numbers` slice and add up all the values.

It’s worth noting that you can also pass a slice to a variadic function by using the `...` operator. For example:

``````package main

import "fmt"

func sum(numbers ...int) int {
result := 0
for _, num := range numbers {
result += num
}
return result
}

func main() {
nums := []int{1, 2, 3, 4, 5}
fmt.Println(sum(nums...))
}``````

Output:

``15``

Variadic functions can be useful in a variety of situations where you need to pass a dynamic number of arguments to a function. For example, you can use a variadic function to process a list of strings:

``````package main

import "fmt"

func join(delimiter string, words ...string) string {
result := ""
for i, word := range words {
if i == 0 {
result = word
continue
}
result = result + delimiter + word
}
return result
}

func main() {
fmt.Println(join(", ", "apple", "banana", "cherry"))
}``````

Output:

``apple, banana, cherry``

In this example, the `join` function takes a `delimiter` string and a variable number of `string` arguments. The function uses a `for` loop to iterate over the `words` slice and join all the values using the `delimiter`.

It’s important to note that you can also pass a single argument to a variadic function. In that case, the function will receive a slice of length 1, rather than a slice of length 0.

Variadic functions can be useful in many situations, but it’s also important to use them judiciously. Overusing variadic functions can lead to code that is harder to understand and maintain. When in doubt, prefer a function with a fixed number of arguments, or use a struct or a map to pass a group of related values.

Posted

in

by

Tags: