Variadic parameters

suggest change

A variadic function accepts any number of trailing arguments of the same type. You declare it by putting ... before the type of the last parameter:

func sum(nums ...int) int

Inside the function, nums is a plain []int slice. You see variadic functions all the time in Go: fmt.Println, fmt.Printf, append, errors.Join, strings.NewReplacer, slices.Insert and filepath.Join are all variadic.

Basics

package main

import "fmt"

func sum(nums ...int) int {
	fmt.Printf("nums: %v, len: %d, type: %T\n", nums, len(nums), nums)
	total := 0
	for _, n := range nums {
		total += n
	}
	return total
}

func main() {
	fmt.Println(sum())
	fmt.Println(sum(5))
	fmt.Println(sum(1, 2, 3, 4))
}
nums: [], len: 0, type: []int
0
nums: [5], len: 1, type: []int
5
nums: [1 2 3 4], len: 4, type: []int
10

The caller passes zero or more int values. The compiler packs them into a new []int and passes that slice to the function. When there are no arguments the slice is nil, so len(nums) is 0 and a range loop simply doesn't run. You don't need a special case for "no arguments".

Mixing regular and variadic parameters

A function can have regular parameters before the variadic one. The variadic parameter must be the last one, and there can be only one:

package main

import (
	"fmt"
	"strings"
)

func joinWith(sep string, parts ...string) string {
	return strings.Join(parts, sep)
}

func logf(level string, format string, args ...any) {
	fmt.Printf("["+level+"] "+format+"\n", args...)
}

func main() {
	fmt.Println(joinWith(", ", "a", "b", "c"))
	fmt.Println(joinWith("-"))
	logf("INFO", "user %s logged in from %s", "alice", "10.0.0.1")
	logf("WARN", "disk almost full")
}
a, b, c

[INFO] user alice logged in from 10.0.0.1
[WARN] disk almost full

Trying to put a regular parameter after the variadic one is a compile error:

func bad(nums ...int, last int) {}
can only use ... with final parameter

Regular parameters are required, so joinWith() with no arguments doesn't compile. Only the variadic part is optional.

Passing a slice with ...

If you already have a slice, you can't pass it directly as a variadic argument. You have to "spread" it with ... after the argument:

package main

import "fmt"

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

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

	// slice expressions work too
	fmt.Println(sum(nums[1:]...))

	// sum(nums) does not compile:
	// cannot use nums (variable of type []int) as int value in argument to sum
}
6
5

... after an argument is only allowed for the final, variadic argument, and you can't mix individual values with a spread slice:

sum(nums)       // cannot use nums (variable of type []int) as int value in argument to sum
sum(0, nums...) // too many arguments in call to sum

If you need to add extra values, build a new slice first: sum(append([]int{0}, nums...)...).

A spread slice is not copied

When you pass individual values, the function gets a freshly allocated slice. When you pass a slice with ..., the function gets that same slice, sharing the underlying array. Modifications inside the function are visible to the caller:

package main

import "fmt"

func double(nums ...int) {
	for i := range nums {
		nums[i] *= 2
	}
}

func main() {
	nums := []int{1, 2, 3}
	double(nums...)
	fmt.Println("after double(nums...):", nums)

	double(nums[0], nums[1], nums[2])
	fmt.Println("after double(a, b, c):", nums)
}
after double(nums...): [2 4 6]
after double(a, b, c): [2 4 6]

The first call doubled the caller's slice in place. The second call got a new slice containing copies of the values, so the caller's nums didn't change.

This matters when a function stores the variadic slice for later use. A caller can modify its slice afterwards and change the data you saved:

package main

import (
	"fmt"
	"slices"
)

type Registry struct {
	names []string
}

func (r *Registry) SetBad(names ...string) {
	r.names = names
}

func (r *Registry) SetGood(names ...string) {
	r.names = slices.Clone(names)
}

func main() {
	input := []string{"a", "b", "c"}

	var r1 Registry
	r1.SetBad(input...)
	input[0] = "CHANGED"
	fmt.Println(r1.names)

	input[0] = "a"
	var r2 Registry
	r2.SetGood(input...)
	input[0] = "CHANGED"
	fmt.Println(r2.names)
}
[CHANGED b c]
[a b c]

If you keep the slice beyond the duration of the call, copy it with slices.Clone (or append([]string(nil), names...)). If you only read it during the call, there's no need to copy.

Nil vs. empty

Since a spread slice is passed as is, the function can see the difference between no arguments, a nil slice and an empty slice:

package main

import "fmt"

func describe(nums ...int) {
	fmt.Printf("len=%d nil=%v\n", len(nums), nums == nil)
}

func main() {
	describe()
	describe(nil...)
	describe([]int{}...)
	describe(1, 2)
}
len=0 nil=true
len=0 nil=true
len=0 nil=false
len=2 nil=false

Calling with no arguments gives nil. A spread empty slice gives that empty, non-nil slice. Code should only care about len(nums) and treat both the same way.

Variadic ...any and fmt.Println

fmt.Println has the signature func Println(a ...any) (n int, err error). Because any accepts any value, you can pass values of different types: fmt.Println("x =", 5, true).

A common surprise is that you can't spread a []string into a ...any parameter. The spread slice is passed as is, without conversion, so it must have exactly the type []any. There's no automatic conversion from []string to []any because they have different memory layouts. You have to convert element by element:

package main

import "fmt"

func main() {
	names := []string{"alice", "bob"}

	// fmt.Println(names...) does not compile:
	// cannot use names (variable of type []string) as []any value in argument to fmt.Println

	args := make([]any, len(names))
	for i, name := range names {
		args[i] = name
	}
	fmt.Println(args...)

	// without ... the whole slice is passed as a single argument
	fmt.Println(names)
	fmt.Println(args)
}
alice bob
[alice bob]
[alice bob]

When you pass a slice without ..., it is passed as a single argument and fmt.Println formats it as [alice bob].

Forwarding variadic arguments

A very common pattern is a wrapper function that forwards its variadic arguments to another variadic function, like a logging helper that calls fmt.Printf. It's easy to forget the ... when forwarding:

package main

import "fmt"

func debugBad(format string, args ...any) {
	fmt.Print("DEBUG: ")
	fmt.Printf(format, args)
}

func debugGood(format string, args ...any) {
	fmt.Print("DEBUG: ")
	fmt.Printf(format, args...)
}

func main() {
	debugBad("%s has %d items\n", "cart", 3)
	debugGood("%s has %d items\n", "cart", 3)
}
DEBUG: [cart %!s(int=3)] has %!d(MISSING) items
DEBUG: cart has 3 items

In debugBad, args is a []any. Without ... the whole slice is passed as one argument, so %s formats the slice [cart 3] and %d has nothing left to format.

The code compiles, but go vet catches this mistake:

main.go:7:2: missing ... in args forwarded to printf-like function

Run go vet regularly, it's part of go test too.

append is variadic

The built-in append takes a slice and any number of elements to add. Use ... to append all elements of another slice:

package main

import "fmt"

func main() {
	a := []int{1, 2}
	b := []int{3, 4, 5}

	a = append(a, 10)
	a = append(a, 11, 12)
	a = append(a, b...)
	fmt.Println(a)

	// special case: append a string to a []byte
	buf := []byte("hello, ")
	buf = append(buf, "world"...)
	fmt.Println(string(buf))

	// prepend by appending to a new slice
	c := append([]int{0}, b...)
	fmt.Println(c)
}
[1 2 10 11 12 3 4 5]
hello, world
[0 3 4 5]

There's a special case: you can append a string to a []byte with ..., which appends the bytes of the string.

See Append to slice and Slice tricks for more.

Requiring at least one argument

A variadic parameter accepts zero arguments. If your function needs at least one value, make the first one a regular parameter. The compiler then enforces it, and you don't need a runtime check:

package main

import (
	"cmp"
	"fmt"
	"slices"
)

func maxOf[T cmp.Ordered](first T, rest ...T) T {
	m := first
	for _, v := range rest {
		if v > m {
			m = v
		}
	}
	return m
}

func setOf[T comparable](items ...T) map[T]struct{} {
	m := make(map[T]struct{}, len(items))
	for _, it := range items {
		m[it] = struct{}{}
	}
	return m
}

func main() {
	fmt.Println(maxOf(3, 9, 2))
	fmt.Println(maxOf("pear", "apple", "zucchini"))
	fmt.Println(maxOf(1.5))

	// maxOf() does not compile: not enough arguments

	fmt.Println(len(setOf("a", "b", "a", "c")))

	// built-in min and max take any number of arguments...
	fmt.Println(min(4, 1, 7), max(4, 1, 7))
	// ...but are not variadic functions: max(nums...) does not compile
	nums := []int{4, 1, 7}
	fmt.Println(slices.Max(nums))
}
9
zucchini
1.5
3
1 7
7

This also shows that variadic parameters work with generics: rest ...T is a []T, and every argument must have the same type T.

The built-in min and max (since Go 1.21) look variadic, but they are not real functions. They accept one or more arguments, but you can't spread a slice into them:

max(nums...) // invalid operation: invalid use of ... with built-in max

Use slices.Min and slices.Max for slices.

Variadic function types

The variadic ... is part of a function's type. You can declare function types, variables and parameters with a variadic signature:

package main

import (
	"fmt"
	"reflect"
)

type Reducer func(nums ...int) int

func apply(name string, r Reducer, nums ...int) {
	fmt.Printf("%s(%v) = %d\n", name, nums, r(nums...))
}

func product(nums ...int) int {
	p := 1
	for _, n := range nums {
		p *= n
	}
	return p
}

func main() {
	apply("product", product, 2, 3, 4)
	apply("count", func(nums ...int) int { return len(nums) }, 7, 8)

	t := reflect.TypeOf(product)
	fmt.Println(t, t.IsVariadic(), t.NumIn(), t.In(0))

	// a func([]int) int is a different type than func(...int) int
	var f func([]int) int
	fmt.Println(reflect.TypeOf(f).IsVariadic())
}
product([2 3 4]) = 24
count([7 8]) = 2
func(...int) int true 1 []int
false

func(...int) int and func([]int) int are different types, even though the parameter is a slice in both cases. You can't assign one to the other. With reflection you can check reflect.Type.IsVariadic(); the type of the last parameter as returned by In() is the slice type []int.

Functional options

Variadic parameters enable the functional options pattern, widely used for configuring objects with optional settings. Each option is a function that modifies the object being built:

package main

import (
	"fmt"
	"time"
)

type Server struct {
	addr    string
	timeout time.Duration
	maxConn int
	tls     bool
}

type Option func(*Server)

func WithTimeout(d time.Duration) Option {
	return func(s *Server) { s.timeout = d }
}

func WithMaxConn(n int) Option {
	return func(s *Server) { s.maxConn = n }
}

func WithTLS() Option {
	return func(s *Server) { s.tls = true }
}

func NewServer(addr string, opts ...Option) *Server {
	s := &Server{
		addr:    addr,
		timeout: 30 * time.Second,
		maxConn: 100,
	}
	for _, opt := range opts {
		opt(s)
	}
	return s
}

func main() {
	s1 := NewServer(":8080")
	s1.print()

	s2 := NewServer(":8443", WithTLS(), WithTimeout(5*time.Second), WithMaxConn(1000))
	s2.print()

	// options can be built up dynamically
	opts := []Option{WithMaxConn(10)}
	if true {
		opts = append(opts, WithTLS())
	}
	s3 := NewServer(":9000", opts...)
	s3.print()
}

func (s *Server) print() {
	fmt.Printf("addr=%s timeout=%v maxConn=%d tls=%v\n", s.addr, s.timeout, s.maxConn, s.tls)
}
addr=:8080 timeout=30s maxConn=100 tls=false
addr=:8443 timeout=5s maxConn=1000 tls=true
addr=:9000 timeout=30s maxConn=10 tls=true

Benefits of this pattern:

Libraries like gRPC (grpc.NewClient(target, opts...)) and zap use this pattern. For a handful of settings a plain config struct is often simpler; functional options shine in public APIs that grow over time.

Performance

Each call with individual arguments creates a slice. That might sound expensive, but the compiler uses escape analysis: if the function doesn't keep the slice after it returns, the backing array is allocated on the stack, which is free:

package main

import (
	"fmt"
	"testing"
)

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

var saved []int

//go:noinline
func keep(nums ...int) {
	saved = nums
}

func main() {
	a := testing.AllocsPerRun(1000, func() { sum(1, 2, 3, 4) })
	b := testing.AllocsPerRun(1000, func() { keep(1, 2, 3, 4) })
	fmt.Println("sum allocs per call:", a)
	fmt.Println("keep allocs per call:", b)
}
sum allocs per call: 0
keep allocs per call: 1

sum only reads the slice, so there's no heap allocation. keep stores it in a global variable, so the slice escapes and must be allocated on the heap for every call. You can see the compiler's decisions with go build -gcflags=-m:

./main.go:9:10: nums does not escape
./main.go:20:11: leaking param: nums
./main.go:25:46: ... argument does not escape
./main.go:26:47: ... argument escapes to heap

//go:noinline is there to prevent inlining, which would hide the effect in such a small program.

Passing values via ...any has an additional cost: each non-pointer value may need to be boxed into an interface, which can allocate. That's one reason why fmt functions are slower than strconv for formatting a single number.

When to use variadic parameters

Variadic parameters work well when:

If callers almost always already have a slice, take a []T parameter instead. strings.Join(elems []string, sep string) takes a slice for that reason. A variadic parameter would force callers to write ... everywhere for no benefit.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents