Variadic functions
A variadic parameter is a final parameter written args ...T. The function receives a []T, and callers may pass zero or more T values, or a slice unpacked with ....
Detailed Explanation
fmt.Println takes any number of arguments. append takes a slice and any number of elements. That is a variadic parameter: one name, a type, and three dots. You use it when the natural call site is a list, not a slice you already built.
Only the last parameter can be variadic. func f(prefix string, ids ...int) is legal. func f(ids ...int, suffix string) is not. Inside f, ids has type []int. It may be nil if the caller passed nothing. len(ids) is the number of extra arguments.
Callers have two forms. f(1, 2, 3) builds a new backing array for the duration of the call. f(existing...) passes the existing slice header. The ... is required when you already have a slice; f(existing) does not compile if existing is []int and the parameter is ...int.
Mutation is shared in the unpack form. If the callee appends to ids and that append stays within capacity, it can overwrite the caller's slice. If the callee only reads, you are fine. Treat a received ...T like any other slice you did not allocate: do not assume you own the array unless you copied it.
any variadic. func log(args ...any) accepts mixed types. fmt uses this. You lose compile-time type checks on the extra arguments. Prefer ...T with a real T when every argument is the same type.
There is no keyword-argument form. You cannot skip a middle variadic slot. Optional flags belong in a struct or in options functions, not in a long ...any list.
What it costs. Each f(1, 2, 3) call allocates (or reuses a small stack buffer) for the slice. In a hot loop, build one slice and pass s..., or take a []T parameter so the allocation is visible. For typical logging and append, the convenience is worth it.
Code Examples
package main
import "fmt"
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println(sum(1, 2, 3)) // 6
vals := []int{4, 5}
fmt.Println(sum(vals...)) // 9
fmt.Println(sum()) // 0, nums is nil
}func join(sep string, parts ...string) string {
if len(parts) == 0 {
return ""
}
out := parts[0]
for _, p := range parts[1:] {
out += sep + p
}
return out
}func appendAll(dst []int, extra ...int) []int {
return append(dst, extra...)
}Common Gotchas
Passing a slice without `...` does not compile
`sum(vals)` is a type error; write `sum(vals...)`.
The callee's `[]T` may share the caller's array
copying before you mutate is the safe default if you did not allocate the slice.
`...any` hides mistakes
a typo becomes a value that `fmt` will print, not a compile error. Use a typed `...T` when you can.
Variadic is only legal as the last parameter
optional earlier arguments need a struct or overloads-by-name, which Go does not have.