We have been talking about functions generally, we’re going to talk about a few more variations on functions about how you can pass the arguments an

Variadic Functions In Golang

submited by
Style Pass
2021-05-27 07:00:05

We have been talking about functions generally, we’re going to talk about a few more variations on functions about how you can pass the arguments and how you can get them to execute at different times.

One useful tool is to be able to pass a variable number of arguments to the function. So, normally when you define a function, you have to hard code the arguments that it takes. So, if it takes three arguments, you list them, comma-separated inside parentheses. for example, let's assume we need to calculate the maximum of three numbers then

when we are finding a maximum of three numbers in this case we know the number of arguments so we created three variables in getMax(num1 float64, num2 float64, num3 float64).

But sometimes you want to make a function that takes a variable number of arguments. So, there are a lot of functions like this, maybe you want to take a number of integers and you don’t know how many integers. If you take two, you take 10, you can still work with them and do the same thing with the whole set of integers regardless of how many are taken. So, in that case, you’d like to be able to pass it a variable number of arguments,

In the above getSum(vals …int) we are accepting a variable number of arguments while calling in the main function. we are initial call passing two arguments,and then we are passing three arguments, so in getSum() we are not defining the number of arguments. and if you see in getSum() we are using vals as a slice. yes, so whenever we are using ellipsis character while declaring variable it will always be treated as a slice in golang.

Leave a Comment