Generators

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 concurrently in this manner is a big draw for a lot of programmers coming to Go from other languages. It gives a succinct method for drawing on the concurrency of the language.

..................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