Go Functions (Part 3) — Variadic Functions

Image for post
Image for post
Photo by Anthony on Unsplash

Variadic functions are functions that are flexible about the number of arguments you can pass into it.

This article is part of the Functions in Go series

Variadic functions are defined using 3 dots, ..., here’s an example of this, where shoppingList ( line 8) is a variadic function.

Line 21: We call the shoppingList function with 3 string arguments.

Line 8: The ...string indicates that “items” is a variadic input parameter. This tells Go to capture all the arguments into a string slice variable called “items”.

Lines 10-11: This confirms that items are indeed a string slice variable that’s housing all the arguments.

Lines 13–15: The for-loop iterates through the slice and prints out each slice entry.

The data type forms part of the variadic input parameter’s definition, e.g. ...int, that’s because the arguments you want the variadic input parameter to capture, must all be of that data type.

So going back to our example, it means the following would fail:

So if you want to pass in arguments of other data types, you can include regular input parameters; however, the variadic input parameter has to be defined last in those cases.

Slices and Variadic Functions

If the arguments you want to use, are stored inside a slice variable, then you can use the ... notation to expand it behind the scenes.

Line 21: We create a new slice variable that contains all the string arguments we want to pass into the shoppingList function’s “items” input parameter.

Line 23: The ... notation here tells Go to auto-expand the slice variable into individual arguments.

You might have realised by now, you can use slices as an alternative to variadic functions, here we’ve rewritten the previous example to use slices instead:

Line 7: We replaced the variadic input parameter with a string slice, []string

Line 23: We removed ... so that the list_of_items slice variable is now passed into the function in its original form.

So it’s really a matter of preference whether or not you decide to write variadic functions in your projects. One thing to keep in mind though is variadic functions have the following constraint:

You can only specify one variadic input parameter in your variadic function

So if you have 2 or more sets of arguments that you want to pass into your function, you can either switch to using slices or, have one variadic function, and use slices for the rest.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store