DEV Community

Teruo Kunihiro
Teruo Kunihiro

Posted on

Variadic functions of Golang

#go

Three dots

Variadic functions can be called with any arguments. Three dots can take an arbitrary number of T(T is same type).

In inside function, it can be used as slice. Aspect of calling Variadic functions, user use very flexible way. Regardless of that the arguments are only one, multiple.
Here is example.

func sum(numbers ...int){
    sum := 0
    for _, num := range numbers {
        sum += num
    }
    return sum
}
sum(1,2,3) //6
sum([]int{1,2,3}...) //6
sum(1) //1
Enter fullscreen mode Exit fullscreen mode

Syntax is simple

If you created the function which wants to receive any number of arguments. You are better to use it.
There are two ways to resolve this situation.

func f(ids []int){
//
}
func service(id int){
    f([]int{id})
}
func service2(id []int){
    f(id)
}
Enter fullscreen mode Exit fullscreen mode

in service, it needs new slice to adjust the arguments of f.
It's a little bit troublesome

Let's use Variadic functions instead of slice.

func f(ids ...int){
//
}
func service(id int){
    f(id)
}
func service2(id []int){
    f(id...)
}
Enter fullscreen mode Exit fullscreen mode

This time, a slice parameter needs three dots the end of name. It means to apply Variadic parameters.

Variadic functions is not only syntax sugar for taking slice parameters, but also helpless to keep the code base simply, and easy to use functions.

Top comments (0)