Search⌘ K

Anonymous Closure

Explore how to pass anonymous closures through Go channels to enable concurrent execution of functions. Understand how closures capture variables and interact with goroutines for synchronized state updates, enhancing your Go concurrency skills.

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:

Go (1.6.2)
package main
import "fmt"
func prod(c chan func()) {
f := <- c
f()
c <- nil
}
func main() {
c := make(chan func())
go prod(c)
x := 0
c <- func() { // puts a closure in channel c
x++
}
fmt.Println(x)
}

The output of this program is 1. At line 11, you ...