March 2020
Intermediate to advanced
406 pages
8h 39m
English
You may be wondering at this point why it's prudent to have anonymous functions and how they pertain to closures. Once we have our anonymous function, we can then utilize a closure in order to reference variables that are declared outside of its own definition. We can see this in the code block that follows:
package main import "fmt" func incrementCounter() func() int { var initializedNumber = 0 return func() int { initializedNumber++ return initializedNumber } } func main() { n1 := incrementCounter() fmt.Println("n1 increment counter #1: ", n1()) // First invocation of n1 fmt.Println("n1 increment counter #2: ", n1()) // Notice the second invocation; n1 is called twice, so n1 == 2 n2 := incrementCounter() ...Read now
Unlock full access