March 2020
Intermediate to advanced
406 pages
8h 39m
English
Generators return the subsequent value in a sequence when a function is called. As you can see in the following code block, anonymous functions can be used to implement the generator iterator pattern in Go:
package main import "fmt" func incrementCounter() func() int { initializedNumber := 0 return func() int { initializedNumber++ return initializedNumber } } func main() { n1 := incrementCounter() fmt.Println("n1 increment counter #1: ", n1()) fmt.Println("n1 increment counter #2: ", n1()) n2 := incrementCounter() fmt.Println("n2 increment counter #1: ", n2()) fmt.Println("n1 increment counter #3: ", n1())}
When incrementCounter() is called, the integer represented in the function is incremented. Being able to use anonymous functions ...
Read now
Unlock full access