Variadic functions In Go

In Go, a variadic function is a function that can accept a variable number of arguments of the same type. The ... syntax is used to indicate a variadic parameter in a function signature. Here’s an example that demonstrates variadic functions:

package main

import "fmt"

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)
}

In this example, the sum function is defined with a variadic parameter numbers of type int. This means that the sum function can accept any number of int arguments.

Inside the sum function, we iterate over the numbers slice using a range loop and accumulate the sum of all the numbers. Finally, the total sum is returned.

In the main function, we call the sum function with five integer arguments. The variadic function allows us to pass multiple arguments as if they were elements of a slice. In this case, the output will be:

Sum: 15

Variadic functions provide flexibility and convenience when dealing with a variable number of arguments. They are commonly used in scenarios where the number of input values can vary, such as calculating sums, concatenating strings, or formatting output.

It’s worth noting that the variadic parameter must be the last parameter in the function signature. You can also pass a slice as an argument to a variadic function by using the ... syntax when passing the slice elements.

Here’s an example that shows both passing individual values and passing a slice to a variadic function:

package main

import "fmt"

func printValues(values ...int) {
    for _, v := range values {
        fmt.Println(v)
    }
}

func main() {
    printValues(1, 2, 3, 4, 5)

    nums := []int{6, 7, 8, 9, 10}
    printValues(nums...)
}

In this example, the printValues function is a variadic function that prints the values passed as arguments. We first call printValues with individual values, and then we call it again with a slice nums, using the ... syntax to expand the slice elements as separate arguments.

The output will be:

1
2
3
4
5
6
7
8
9
10

Variadic functions provide a flexible and concise way to work with a varying number of arguments, enhancing the versatility of your Go code.