Golang Variadic Functions Example

Go (Golang) as also other major programming languages supports variadic functions. Variadic functions are functions that accept a variable number of arguments of the same type. Also defined as, functions of indefinite arity.

Variadic functions are particularly useful when passing a variable number of arguments to your Go functions.

How to define a variadic function in Go (Golang)

To define a variadic function you can just add

func multiply(args ...int)

three dots followed by the type your variadic arguments belong to. In our case args it’s just a slice of int and you can range over it like any other regular slice.

How to use a variadic function in Go (Golang)

To pass arguments to a variadic function you can just pass any arbitrary argument as long as the type is what you have defined in your function signature. You can also pass zero arguments

multiply()
multiply(1)
multiply(1, 2, 3, 4)

Variadic Function Example in Go (Golang)

Let’s see a couple of examples to clear things up.

package main

import (
    "fmt"
)

func main() {
    fmt.Println(multiply())
    fmt.Println(multiply(2))
    fmt.Println(multiply(1, 2, 3))
    fmt.Println(multiply(1, 2, 3, 4, 0))
}

func multiply(args ...int) int {
    acc := 1
    for _, n := range args {
      acc *= n
    }

    return acc
}

The above programs returns the following

1
2
6
0

You can also run this example on the Go playground

Use a slice with a variadic function in Go (Golang)

You can also pass a slice directly to a variadic function in Go (Golang) as long as you use the following notation.

nums := []int{1, 2, 3, 4}
multiply(nums...)

The above notation allows you to pass a slice into a variadic function directly just by using the ... operator. You can check more slice tricks in the official Go Wiki

Let’s see a full example on how to pass a slice to a variadic function in Go

package main

import (
    "fmt"
)

func main() {
    fmt.Println(multiply([]int{}...))
    fmt.Println(multiply([]int{2}...))
    fmt.Println(multiply([]int{1, 2, 3}...))
    fmt.Println(multiply([]int{1, 2, 3, 4, 0}...))
}

func multiply(args ...int) int {
    acc := 1
    for _, n := range args {
      acc *= n
    }

    return acc
}

The above programs returns the following

1
2
6
0

You can also run this example on the Go playground


Ready for your next Go Job? Submit your profile and get hired on Golang Cafe