In Go, it’s pretty easy to write an anonymous function.
package main
import "fmt"
func main() {
func(s string){
fmt.Println("s is:", s)
}("hello world")
}
Running the above code produces:
$ go run main.go
s is: hello world
You can even assign the anonymous function to a variable like so:
package main
import "fmt"
func main() {
myFunc := func(s string){
fmt.Println("s is:", s)
}
myFunc("hello again, world!")
}
Now we get this output from the above code:
$ go run main.go
s is: hello again, world!
So now let’s talk about closures. You can use closures to wrap around (or “close over”) an anonymous function while maintaining some state…
Here we define the counter()
function which a user calls with an initial integer. It returns a function which increments and returns the function every time it is called. The neat part is that the state is (a) preserved between calls and (b) unique to each instance.
package main
import "fmt"
func counter(i int) func() int {
return func() int {
i++
return i
}
}
func main() {
ctr1 := counter(10)
fmt.Println("ctr1():", ctr1())
fmt.Println("ctr1():", ctr1())
fmt.Println("ctr1():", ctr1())
ctr2 := counter(55)
fmt.Println("ctr2():", ctr2())
}
The above code gives you this output when run:
$ go run main.go
ctr1(): 11
ctr1(): 12
ctr1(): 13
ctr2(): 56