Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 147 ยท Functions

Variadic Functions

Learn Go variadic functions - the ...T parameter, calling with zero or many arguments, spreading a slice with ..., how fmt.Println uses ...any, and the aliasing pitfall.

Some functions naturally take "as many as you like": fmt.Println prints any number of values, append adds any number of elements, and a sum function should not care whether you pass two numbers or twenty. In Go these are variadic functions. The last parameter of the function is written with three dots in front of its type, and the caller can supply zero, one or many arguments for it.

This lesson shows how to declare and call variadic functions, how to pass an existing slice into one with ..., how fmt.Println(a ...any) works under the hood, and a subtle aliasing bug that catches many Go programmers. It builds on Functions and Multiple Return Values.

Declaring a variadic parameter

Put ... before the type of the final parameter. Inside the function, that parameter is an ordinary slice of the given type:

Go A variadic sum function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

numbers has the type []int. With no arguments it is a nil slice, which range and len handle without any special case, so sum() returns 0. With arguments, Go builds a new slice holding them.

You can check the type and length yourself:

Go What the variadic parameter looks like inside

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The output shows []string each time, and nil=true only when you passed nothing. Only the last parameter can be variadic, and there can be only one. Parameters before it are normal and required, like label here.

A variadic parameter is a convenience at the call site. For the function's own code it is just a slice, so everything from Slices applies: indexing, len, range, slices.Max and so on.

Passing a slice with ...

What if you already have a slice and want to call a variadic function with its elements? Add ... after the slice in the call. That passes the slice itself as the parameter, without copying:

Go Spreading a slice into a variadic call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You can't mix the two styles: join("-", "a", date...) doesn't compile, because with ... the slice must be the only value for that parameter. The element type must match exactly as well:

Go Wrong slice type for the spread (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler answers ./main.go:15:18: cannot use values (variable of type []int64) as []int value in argument to sum. Go never converts slice types implicitly, so you would have to build a []int first.

The empty interface and fmt.Println

The most famous variadic function is fmt.Println(a ...any). Because any is the type that accepts every value, one function handles a mix of types:

Go A variadic function that accepts anything

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice fmt.Println(parts...): parts is already a []any, so spreading it forwards the arguments untouched. The last call shows a classic annoyance: a []string is not a []any, even though every string fits in an any. The two slices have different memory layouts, so you must copy element by element, as the loop does. Generics (Generics: Type Parameters) remove many of these conversions, and The Empty Interface and any explains any in depth.

Practical patterns

A required first argument

A function like max needs at least one value. Require it with a normal parameter before the variadic one, so the compiler enforces it:

Go Requiring at least one argument

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Optional settings

Variadic parameters are also the base of the functional options pattern: a constructor takes opts ...Option so callers can pass any combination of settings. Constructors, Options and Builders develops it fully, and Functions as Values shows a first taste.

Formatting helpers

Functions like fmt.Printf(format string, a ...any) and fmt.Sprintf put the format first and the variadic list last. When you wrap them, forward with ...:

Go Wrapping Sprintf correctly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

go vet recognizes wrappers like this one (it is named Printf and forwards to fmt.Printf) and checks the format string at each call site, so mismatched verbs are still reported.

The aliasing pitfall

When you call a variadic function with slice..., the function receives your slice, not a copy. If it modifies the elements, you see the change:

Go A variadic function that changes the caller's data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

With data... the function writes into data's backing array, so the first element becomes 0. With separate arguments, Go creates a brand-new slice, and a and b are untouched. If a variadic function stores the slice it receives (in a struct field, say) and the caller later changes their slice, the stored data changes too. When in doubt, make a copy with slices.Clone or append([]T(nil), values...).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside func f(nums ...int), what is the type of nums?

    A variadic parameter is received as a slice of its element type, here []int. It is nil when no arguments are passed.
  2. 2. Which call is valid for func f(prefix string, parts ...string) when s := []string{"a", "b"}?

    A spread slice must be the only value for the variadic parameter, and the earlier parameters must still be given. f("x", s...) does both.
  3. 3. Why does fmt.Println(names...) fail to compile when names is a []string?

    Println takes a ...any, meaning []any. Slice types are never converted implicitly, even when each element converts. Copy into a []any first.
  4. 4. After zeroFirst(data...) where the function sets values[0] = 0, what happens to data?

    Spreading passes the slice itself, so writes through it reach the caller's backing array.
  5. 5. How many variadic parameters can a function have, and where?

    Only the final parameter can be variadic, and there can be only one.

Summary

  • func f(args ...T) accepts zero or more T arguments; inside, args is a []T (nil when empty).
  • Only the last parameter can be variadic; earlier parameters can force a minimum number of arguments.
  • f(slice...) passes an existing slice directly, without copying, so the function can modify your elements.
  • You can't mix individual arguments and a spread in one variadic position, and the slice type must match exactly ([]string is not []any).
  • Forward variadic arguments to other functions with args...; this is how wrappers around fmt.Printf work.
  • Variadic parameters power conveniences like append and the functional options pattern.

Next: Anonymous Functions and Closures shows how to create functions on the fly and how they remember variables.