← Back Home

Variadic functions in Go

  1. golang
  2. functions

Let’s create a function that we can pass 3 numbers as arguments and them it returns the average of this numbers.

func average(num1, num2, num3 float64) float64 {
    avg := (num1 + num2 + num3) / 3

    return avg

and then, you call it like this

func main() {
    fmt.Println(average(2, 4, 6))

Le’ts run to see if works

$ go run average.go

It works. Super easy, but not so useful. Normally, when you want to calculate the average, you don’t know how many arguments you will need to accept. How can we handle this?

When you have a function that you can’t determinate the number of arguments you are going to pass then you need a Variadic function.

So, to do this, we just need use ‘…’ before the parameter type on the function.

func average(numbers ...float64) float64 {
 // ...

But now, we don’t have separated values anymore, the …float64 will be transformed in a slice of float64 and we need to iterate over the items to calculate the average.

func average(numbers ...float64) float64 {
    var total float64
    for _, num := range numbers {
        total += num

    return total / float64(len(numbers))

This is a Variadic function in Go and we can pass as many arguments we want.

func main() {
    fmt.Println(average(2, 4, 6, 9, 5, 3, 12))