Pravar Agrawal Technology & Travel

Go - Closures & Variadic functions

“The best programming language is the one which works best for you and the one which you are most comfortable with” - Kelsey Hightower

I really like this quote from Kelsey Hightower as it really solves the most confusing question of all time, which programming language is best? Even though I’ve been working with Go for a while, I still come along it’s new features especially whenever I run into a new problem. In this post, I’ll discuss about some amazing features like Variadic Functions, Go Closures which makes Go one of the most flexible and popular language for microservices today.

The Go programming language was written keeping simplicity in mind. One of the features of Go which I’ve felt is quite simple yet elegant is Closures. A Closure, is a type of anonymous function which is written like a function declaration but without a name following the func keyword. For example:

func add() func() int {
	var x, y, z int
	return func() int {
		z = x+y
		return z

The above function add returns another function of type func() int. A call to add creates local variables x, y, z and returns an anonymous function that, each time it’s called does an addition of x & y and returns the sum z. Now, how these closures are useful to us? One of the main usage of closures is with the standard library of Go, like the sort package. This package has some helpful functions and code for sorting and searching lists like sorting a slice of integers. Another common usage of closures is to wrap data inside of a function that otherwise wouldn’t typically be available.

One more useful feature of Go is the variadic functions. A variadic function is the one which can be called with varying number of arguments, like fmt.Printf the most familiar example. The way we declare a variadic function is, the final parameter is preceded by an ellipsis, “…” and that indicates that the function may be called with any number of arguments same type. For example:

func add(values int {
	sum := 0
	for _, value := range values {
	sum += value
	return sum

The above add function returns the sum of zero or more int arguments. Now, within the function body the type of vals is an []int slice. When the add is called, any number of values may be provided for its values parameter,

	fmt.Println(add())          // "0"
	fmt.Println(add(5))         // "5"
	fmt.Prinltn(add(1, 4, 8, 9))  // "22"

Variadic functions are quite commonly used for string formatting and also when we want to skip creating a temporary slice. Instead, we can pass the input parameters to a function directly.

Go is full of such cool features, like the ones we read above. We can’t deny the fact that Go is one of the most popular languages when it comes to microservice development. I’ll be back with more cool features of Go in my next few posts. Until next time!!