I hadn’t come across this concept in previous languages I worked in.  In Go, however, this concept came up in an online course I was taking on Udemy.com (from Todd McLeod.)  He raised the concept of a Function.

These are which take an unspecified amount of parameters.  In a regular function you would lock down what parameters are allowed (how many and of what types.)  In a Variadic Function, you use “…” notation to allow for an undefined amount values to get passed.

Go is not the only language to use Variadic Functions.  Other languages that make use of this (even using the same triple dot notation) are:

Python and Ruby also make use of this concept, although with a different notation (the asterisk.)

Here’s some code showing a variadic function in Golang:

``````package main
import "fmt"

func main(){
}

fmt.Println(names)

for _, name := range names {
fmt.Println(name)
}
}

// The Variadic function allows for multiple params to be passed in.
// Notation of this is in the form of ...
// These params are put into an array.
// Also note the for loop making use of a blank identifier (the underscore)
// The blank identifier allows me to ignore the key of the array and only concern myself with the value.``````

I the above example, the code will output the collection/array (fmt.Println(names)) as well loop through the array and output each name passed in.  Here’s the outuput:

[Brian Austin Lisa Travis Dan]
Brian
Austin
Lisa
Travis
Dan

It is possible to have a variable function and you want to pass into it data from a slice.  The data could be like this (taken from Todd McLeod’s course): data := []float64{43, 24,10,24,33,54}

That data can not simply be passed into a variadic function.  Instead, the call to the function needs to be modified like so:

multip(data…)

func multip(num …float64){ }

What is occurring in this situation is that the call to the method is using a variadic parameter (triple dots appended to the param.)  This sends each element to the function, one at a time.  So first 43 is sent into the multip function, then 24, then 10 and so on.

For more info on these topics, check out Todd McLeod’s course: Learn to Code using Go