Accepting Variable Number of Arguments in a Function
Software Engineer with an entrepreneurship gene. Love talking about code, products, UI/UX and how to build startups.
Search for a command to run...
Software Engineer with an entrepreneurship gene. Love talking about code, products, UI/UX and how to build startups.
No comments yet. Be the first to comment.
Goroutines are one of the best features of Go language. It is very easy to run a function as a goroutine, you just have to use the keyword go before the function call. Here is a very simple function which sleeps for n seconds and prints a line. pa...

In a previous post, we saw how we can use Regular expressions in Go to match and replace patterns in a string. While regexps are very useful, you might not want to them for every time you want to do some basic string manipulation. The strings package...

Go is a modern language, but doesn't use try-except blocks to handle errors. Errors are simple values that can be returned from functions and it is common to check for errors before proceeding with your next steps. Let's see the different ways to cre...

In the previous post, we saw how to write a simple unit test case and also how to write table driven test cases. In this post we will quickly see how to write benchmarks, as go supports running benchmarks on your functions as part of the standard tes...
Go has built-in support for writing test cases for your code. And it is important to write as much test cases as possible to make sure you cover all possible conditions. You have to use the testing standard package to write your unit test cases. Let...
Pro Golang Dev
14 posts
Functions in Go are capable of accepting multiple number of arguments, also called as variadic functions. One prominent example of such a function is fmt.Println as you can pass in any number of variables, it will print each of them separated by a space.
The way to define a variadic function is to prepend the data type with three dots. That variable is now accessible as a slice and can be iterated.
Here is a simple example which explains it.
func sum(numbers ...int) int {
total := 0
for _, n := range numbers {
total += n
}
return total
}
This is a simple sum function, which iterated through all numbers and returns back the total. Now to call this function, you just pass all the numbers as separate arguments.
total := sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
By declaring the argument as a ...int, your numbers variable is now passed into the function as a slice of integers. But what if you already have a slice of numbers and want to pass it to this function?
numbers := []int{1,2,3,4,5}
total := sum(numbers...)
You just have to pass in the slice followed by three dots to unwrap the slice into individual parameters to the function.