Working with Variadic Functions in Go

11.22.2021

Intro

Variadic functions allow you to pass a variable number of arguments. If you are creating a function, but want to allow for various arguments, you can use a variadic function. For example. The Println function in the fmt package allows you to pass in many different variables. In this article, we will learn how to work with Variadic function in Go.

Creating a Variadic Function

To create a variadic function, we can use the ... operator when defining the variables. Each use of ... must use the same type. Here is an example.

func printVariadic(text ...string) {
	fmt.Println(text[0])
	fmt.Println(text[1])
}


func main() {
	printVariadic("one", "two")
	printVariadic("one", "two", "three")
}

Notice in the example above, we call the function twice with a different list of variables. We can then access this variable like an array, where text[0] is the first string variable.

We can also combine variadic parameters with other parameters. Our variadic parameter must come last.

func printVariadic(text string, nums ...int) {
	fmt.Println(text)

	fmt.Println(nums[0])
	fmt.Println(nums[1])
}


func main() {
	printVariadic("one", 1, 2, 3)
	printVariadic("one", 1, 2)
}

Finally, we can mix types by combining ... with the interface{} definition.

func printVariadic(args ...interface{}) {
	for _, value := range args {
		fmt.Println(value)
	}
}


func main() {
	printVariadic("one", "two", 10.5, []int{1, 2, 3})
	printVariadic("one", "two", "three", 1, 2)
}

The Full Example

Here is the full example code. You can run this by copying the contents into a file called main.go and then running go run main.go.

package main

import "fmt"

func printVariadic(text ...string) {
	fmt.Println(text[0])
	fmt.Println(text[1])
}

func printVariadic2(text string, nums ...int) {
	fmt.Println(text)

	fmt.Println(nums[0])
	fmt.Println(nums[1])
}

func printVariadic3(args ...interface{}) {
	for _, value := range args {
		fmt.Println(value)
	}
}

func main() {
	printVariadic("one", "two")
	printVariadic("one", "two", "three")

	printVariadic2("one", 1, 2, 3)
	printVariadic2("one", 1, 2)

	printVariadic3("one", "two", 10.5, []int{1, 2, 3})
	printVariadic3("one", "two", "three", 1, 2)
}