Variadic Functions in Go

Learn via video courses
Topics Covered

Overview

A variadic function is a function of an indefinite input argument, i.e., one which accepts a variable number of arguments. In this article, We will learn about variadic functions in Golang and write some examples.

Introduction

A function is a piece of code dedicated to performing a particular job. A function takes one or many arguments and may return one or many values. It is used to reduce redundancy in our program.

Variadic functions are functions that take a variable number of arguments. This makes our code much more readable as we are just passing arguments to our function.

Golang Variadic Functions

To declare a variadic function, the type of the final parameter is preceded by an ellipsis ("…"). This represents that the function can handle a variable number of arguments of the type passed.

This type of function is useful when we do not know the size of the input. The best example in golang that is a variadic function is Println from the fmt package.

golang-variadic-functions

[name=shubhamdeshmukh] update f to myFunc, and replace variadic with an ellipsis.

Syntax of Variadic Functions

In Golang, We can create a variadic function as below,

Examples of Variadic Functions

  • Examples to add numbers and return their sum

    Output:

    Example on playground : playground link

  • Passing an array to a variadic function

    Output:

    Example on playground : playground link

When We Use a Variadic Function?

  • Variadic functions can be used when the input size to the function is not known to us.
  • They can be used to replace slice as an argument type.
  • Variadic function increases the readability of your program.
  • When our data for the function is coming from different data structures, Then we should go for a variadic function which avoids the creation of a new slice just to pass it to the function.

Using Slice Instead of Variadic Functions

  • slices should be used instead of a variadic function if we know the size of the argument.
  • We can not use variadic type as the return type of a function. We can use slices to return our data.
  • we can pass a slice as input to a variadic function by adding an ellipsis in the argument.

Conclusion

  • Learnt about Variadic functions in Golang.
  • Implemented examples showcasing the Variadic function.