Anonymous Functions
Not only can you assign functions to variables, you can also define new functions within a function and assign them to variables.
These inner functions are anonymous functions; they don’t have a name. You don’t have to assign them to a variable, either. You can write them inline and call them immediately. Here’s a simple example that you can run on The Go Playground:
func main() { for i := 0; i < 5; i++ { func(j int) { fmt.Println(“printing”, j, “from inside of an anonymous function”) }(i) } }
You declare an anonymous function with the keyword func immediately followed by the input parameters, the return values, and the opening brace. It is a compile-time error to try to put a function name between func and the input parameters.
Just like any other function, an anonymous function is called by using parenthesis. In this example, we are passing the i variable from the for loop in here. It is assigned to the j input parameter of our anonymous function.
Running the program gives the following output:
printing 0 from inside of an anonymous function printing 1 from inside of an anonymous function printing 2 from inside of an anonymous function printing 3 from inside of an anonymous function printing 4 from inside of an anonymous function
Now, this is not something that you would normally do. If you are declaring and executing an anonymous function immediately, you might as well get rid of the anonymous function and just call the code. However, there are two situations where declaring anonymous functions without assigning them to variables is useful: defer statements and launching goroutines. We’ll talk about defer statements in a bit. Goroutines are covered in Chapter 10.