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 Variadic Function.
Variadic Functions
These are functions 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.
Languages Using Variadic Functions
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:
- C++
- Java
- JavaScript
Python and Ruby also make use of this concept, although with a different notation (the asterisk.)
Examples of Variadic Functions in Go
Here’s some code showing a variadic function in Golang:
[pastacode lang=”c” manual=”package%20main%0Aimport%20%22fmt%22%0A%0Afunc%20main()%7B%0A%09variadicsf(%22Brian%22%2C%20%22Austin%22%2C%20%22Lisa%22%2C%20%22Travis%22%2C%20%22Dan%22)%0A%7D%0A%0Afunc%20variadicsf(names%20…string)%7B%0A%09fmt.Println(names)%0A%0A%09for%20_%2C%20name%20%3A%3D%20range%20names%20%7B%0A%09%09fmt.Println(name)%0A%09%7D%0A%7D%0A%0A%2F%2F%20The%20Variadic%20function%20allows%20for%20multiple%20params%20to%20be%20passed%20in.%0A%2F%2F%20Notation%20of%20this%20is%20in%20the%20form%20of%20…%0A%2F%2F%20These%20params%20are%20put%20into%20an%20array.%0A%2F%2F%20Also%20note%20the%20for%20loop%20making%20use%20of%20a%20blank%20identifier%20(the%20underscore)%0A%2F%2F%20The%20blank%20identifier%20allows%20me%20to%20ignore%20the%20key%20of%20the%20array%20and%20only%20concern%20myself%20with%20the%20value.%0A” message=”” highlight=”” provider=”manual”/]
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
Other Variadic Forms
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
Comments are closed