← Back to Go Course | Chapter 4: Functions | Lesson 4 of 7

Variadic Functions

A variadic function is like a bag that can hold any number of items -- you can hand it zero, one, or a hundred arguments and it just gathers them all up.

Declaring a Variadic Function

Prefixing the last parameter's type with '...' lets the caller pass any number of arguments of that type, including none at all -- inside the function, that parameter is just a regular slice.

Example: Declaring a Variadic Function

markup
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, 4))
	fmt.Println(sum())
}

Spreading a Slice into Variadic Arguments

If you already have a slice and want to pass its elements as individual variadic arguments, append '...' after the slice at the call site instead of passing the slice as one value.

Example: Spreading a Slice into Variadic Arguments

markup
package main

import "fmt"

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

func main() {
	values := []int{10, 20, 30}
	fmt.Println(sum(values...))
}

Mixing Regular and Variadic Parameters

A variadic parameter can be combined with regular parameters before it, as long as it remains the final parameter in the list -- a common pattern for functions like a formatted logger that always takes a prefix plus a variable number of values.

Note: Variadic parameters must always come last in the signature.

Example: Mixing Regular and Variadic Parameters

markup
package main

import "fmt"

func logAll(prefix string, values ...int) {
	for _, v := range values {
		fmt.Println(prefix, v)
	}
}

func main() {
	logAll("value:", 1, 2, 3)
}
Common Mistakes
  1. Forgetting the variadic parameter must be last in the parameter list -- Go only allows one, at the very end.
  2. Trying to pass a slice directly to a variadic parameter without the '...' spread operator, which fails to compile.
  3. Assuming a variadic function can accept zero arguments and behave the same as passing an empty slice, without checking len() first.
Chapter Summary
  • A variadic parameter, written as '...Type', lets a function accept any number of arguments of that type.
  • Inside the function, the variadic parameter behaves like a regular slice.
  • An existing slice can be passed to a variadic parameter using the spread operator, slice...
  • Only the last parameter in a function signature may be variadic.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.