November 2017
Intermediate to advanced
670 pages
17h 35m
English
Let's look at a few simple code examples to understand the difference between an anonymous function and a closure.
Here's a typical named function:
func namedGreeting(name string) { fmt.Printf("Hey %s!n", name)}
The following is an example of the anonymous function:
func anonymousGreeting() func(string) { return func(name string) { fmt.Printf("Hey %s!n", name) }}
Now, let's call them both and call an anonymous inline function to say Hey to Cindy:
func main() { namedGreeting("Alice") greet := anonymousGreeting() greet("Bob") func(name string) { fmt.Printf("Hello %s!n", name) }("Cindy")}
The output will be as follows:
Hello Alice!Hello Bob!Hello Cindy!
Now, let's look at a closure named ...