Go by Example

Variadic Functions

A variadic function accepts a variable number of arguments via the ...T parameter - the basis of fmt.Println, append, and ergonomic APIs.

A variadic parameter accepts zero or more arguments of one type. It must be the last parameter. Inside the function it behaves like a slice, a list of values that can change in length.

Pass separate values as usual. To pass an existing slice, add ... at the call site to supply its elements as arguments.

package main
 
import "fmt"
 
func sum(nums ...int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}
 
func main() {
    values := []int{10, 20, 30}
    fmt.Println(sum(1, 2, 3))
    fmt.Println(sum(values...))
}

In production

Passing values... supplies each item from the slice as an argument. The items are not copied, so changing one through the parameter can also change the caller's slice. Use a regular slice parameter when the function needs to keep or change the list.

Enjoyed this? Get more software craft delivered to your inbox.