Anonymous Closure
In this lesson there is a detailed description of how to use closures along with a channel.
We'll cover the following...
Passing anonymous closure through a channel
Functions are values in Go, and so are closures. So, we can construct a channel c
, whose data type is a function, as in the following example:
Press + to interact
package mainimport "fmt"func prod(c chan func()) {f := <- cf()c <- nil}func main() {c := make(chan func())go prod(c)x := 0c <- func() { // puts a closure in channel cx++}fmt.Println(x)}
The output of this program is 1. At line 11, you ...