← 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.
Syntax
go
func name(fixed type, args ...type) returnType {
    // args is []type
}

name(a, b, c)
name(a, slice...)

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
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// Define the function sum
func sum(nums ...int) int {
	// Short declaration: create total and infer the type
	total := 0
	// Loop over nums; the blank identifier _ ignores the index
	for _, n := range nums {
		total += n
	}
	// Send total back to the caller
	return total
}

// main is where the program starts running
func main() {
	// Print the values followed by a newline
	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
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// Define the function sum
func sum(nums ...int) int {
	// Short declaration: create total and infer the type
	total := 0
	// Loop over nums; the blank identifier _ ignores the index
	for _, n := range nums {
		total += n
	}
	// Send total back to the caller
	return total
}

// main is where the program starts running
func main() {
	// Short declaration: create values and infer the type
	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
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// Define the function logAll
func logAll(prefix string, values ...int) {
	// Loop over values; the blank identifier _ ignores the index
	for _, v := range values {
		// Print the values followed by a newline
		fmt.Println(prefix, v)
	}
}

// main is where the program starts running
func main() {
	logAll("value:", 1, 2, 3)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.