Variadic Functions

Variadic Functions


Certain functions can take a variable number of arguments. These functions are known as variadic functions. fmt.Println is such a function.


fmt.Println("A")
fmt.Println("A","1","3","@","X",".","COM")


Most functions only take the number of arguments matching the number of parameters in the function signature.


func z(x int, y int)

for example, can only accept to arguments.

z(1,2)

Variadic functions, such as Println, have a special last parameter.

func z(x int, y …int)

The three periods before the last parameter type mark this as a variadic function. NOTE: This is/are three periods … and not an ellipsis character. The function can now take any number of arguments, the last one is returned as a slice. Here is what it looks like in action.


Screen Shot 2021-05-17 at 8.05.34 AM


Screen Shot 2021-05-17 at 8.05.48 AM

As you can see if I omit the variadic argument, the parameter returns an empty slice.

A couple of things to note:
  • The variadic parameter must be the last one in the signature, and "There can only be one."
  • The parameters passed to the variadic parameter must be of the same time as the data type of the variable. In the above example, I can't mix strings into the list of parameters. I'll get an error.

Once I have the slice, I can do whatever I want with it.


I can also pass a slice to the variadic parameter. To do this I have append the three periods after the slice I pass in. In the final line of main(), I pass in a slice as:

myInts…

Screen Shot 2021-05-17 at 8.16.45 AM



Screen Shot 2021-05-17 at 8.17.31 AM

So, the thing I need to remember is that when I pass in multiple items to the variadic parameter, the function treats them as a slice. When I pass a slice into the parameter, I don't get a slice containing another slice; I just get the same slice back. If I pass a slice in, I get the same thing out.


That's it for today. I don't use variadic functions often, but when I need them, it's nice to know how to use them.


This site does not track your information.