Sometimes you need a function to be bound to a variable. Other times it is beneficial pass a function as an argument to another function. In this post, we will be looking at anonymous functions in Go. These anonymous functions allow us to create closures, easily pass around functions as arguments, and pass functions as returns.  

Anonymous Functions in Go

Anonymous functions are called such because they have no name associated with them. This can be very useful for code that we only want to be executed in certain situations. For instance, we can pass an anonymous function as an argument for another function. We can also make a function return another function. Let’s look at some simple examples.

In these examples, we have one function which takes a function as an argument. Our function declaration explicitly states that it takes a specific type of function. In this case, we are taking in a function that takes in a string and returns a string. This type of function, the argument function, is commonly called a callback function. 

We also have a function that returns a function. This function takes in no arguments and it returns a function that takes in an integer and returns an integer. Our return function is commonly referred to as a closure. Both of these types of functions are examples of higher-order functions in Go.

First Class Functions and Closures

Go features first-class functions. This basically means that Go treats functions as it would any data structure. You can pass functions as arguments, return them from other functions, and you can store them in variables. There are also other data structures that can be used to store functions which we will get into later. 

Let us talk about closures for a second here. A closure as its name implies is a function that closes off another function. We can use closures to specifically set the initial “environment” and have that “environment” be stored for all instances of the function.court-closure

If you look at this example, our outer function gives our inner function access to its variables. This means that those variables are only accessed by the inner function and the outer function which makes it easier to control how they are changed. Our closure is not returning a function, but it creates a closed scope for these functions and it creates a consistent initial environment. 

Conclusion

In this post, we looked at anonymous functions in Go. We talked about how we can use anonymous functions to create closures. We also looked at first class functions, higher order functions, and callback functions in Go. In our next few posts, we will talk about scope and look at pointers, structs, and interfaces in Go.