GOLANG

Variadic functions in Go

A variadic function accepts an infinite number of arguments and all these arguments are stored in a parameter of the slice type.

Uday Hiwarale
RunGo
Published in
4 min readOct 14, 2018

--

(source: pexels.com)

What is a variadic function?

As we have seen in a functions lesson, a function is a piece of code dedicated to perform a particular job. A function takes one or many arguments and may return one or many values.

Variadic functions are also functions but they can take an infinite or variable number of arguments. Sounds stupid but we have seen this in slices lesson when append function accepted a variable number of arguments.

func f(elem ...Type)

A typical syntax of a variadic function looks like above. ... operator called as pack operator instructs Go to store all arguments of type Type in elem parameter. With this syntax, Go creates elem variable of the type []Type which is a slice. Hence, all arguments passed to this function is stored in a elem slice.

Let’s take an example of append function.

append([]Type, args, arg2, argsN)

append function expects the first argument to be a slice of type Type, while there can be a variable number of arguments after that…

--

--