Variadic Functions

Variadic functions can take zero or more final arguments of a specific type.

Syntax

You use the triple dot ... before the type in the function signature. The variadic arguments are received by the function as a slice.

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

sum(1, 2, 3) // nums is []int{1, 2, 3}

The Spread Operator

If you already have a slice and want to pass it into a variadic function, you can use the spread operator (...) at the call site.

names := []string{"Alice", "Bob"}
printStrings(names...) // Unpacks the slice into individual arguments

Common variadic functions in the standard library include fmt.Println and append.