Anonymous functions

The first step to understanding closures in Go is to understand anonymous functions. An anonymous function is created using a variable for the inception of the function. They are also functions that don't have a name or identifier, hence the name anonymous functions.

A normal function invocation to print Hello Go to the screen would be what is shown in the following code block:

func HelloGo(){
fmt.Println("Hello Go")
}

Next, we could call HelloGo() and the function would print a Hello Go string.

If we wanted to instantiate our HelloGo() function as an anonymous function, we would invoke this as referenced in the following code block:

// Note the trailing () for this anonymous function invocation
func() {
fmt.Println("Hello Go")
}()

Our preceding anonymous function and the HelloGo() function are lexically similar.

We could also store a function as a variable for use later on, as referenced in the following code block:

    fmt.Println("Hello Go from an Anonymous Function Assigned to a Variable")
}

All three of these things – the HelloGo() function, our anonymous function, and the function assigned to the hello variable – are lexically similar.

After we've assigned this hello variable, we could then call this function using a simple invocation of hello(), where our preceding defined anonymous function would be called and Hello Go would be printed to the screen in the same fashion that it was printed in our previously called anonymous function.

We can see how each of these work in the following code block:

package main

import "fmt"

func helloGo() {
fmt.Println("Hello Go from a Function")

}

func main() {
helloGo()
func() { fmt.Println("Hello Go from an Anonymous Function") }()
var hello func() = func() { fmt.Println("Hello Go from an Anonymous Function Variable") }
hello()
}

The output from this program shows three print statements, all similar, with small differences in print to show how they were returned in the following screenshot:

Anonymous functions are a powerful aspect of Go. As we continue this chapter, we'll see how we can build on them to make some very useful things.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.214.155