DEV Community

Teruo Kunihiro
Teruo Kunihiro

Posted on

5

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay