Understand the contract

A variadic function accepts a variable number of arguments of one type. Declare its final parameter with ...T. Inside the function that parameter behaves as a []T slice. This fits operations such as adding numbers or formatting several values while keeping the element type explicit.

You can call sum with individual integers or expand an existing []int using values.... The variadic parameter must be last, so ordinary required parameters come first. A call with no variadic arguments provides a nil slice; range over it performs no iterations.

Work through the example

The example prints zero, six and nine. The no-argument sum returns the additive identity, zero, because total starts at its zero value. For another operation, such as a minimum, the empty-input case may require a boolean or error instead of inventing a result.

package main

import "fmt"

func sum(values ...int) int {
    total := 0
    for _, value := range values { total += value }
    return total
}

func main() {
    fmt.Println(sum())
    fmt.Println(sum(1, 2, 3))
    values := []int{4, 5}
    fmt.Println(sum(values...))
}

Watch this boundary

Expanding an existing slice does not make its elements independent. A variadic function that modifies values[i] can modify the caller’s slice. Keep read-only operations read-only, or document mutation and copy the input before changing it when that is the intended ownership contract.

Practice with a changed input

Implement joinWith(separator string, values ...string). Try zero, one and three values, then pass a preexisting slice using the expansion syntax.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services