Closures PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Go by Example: Closures

Go supports anonymous functions, which can form


closures. Anonymous functions are useful when you
want to define a function inline without having to
name it.

package main

import "fmt"

This function intSeq returns another function, which func intSeq() func() int {
we define anonymously in the body of intSeq. The i := 0
returned function closes over the variable i to form a return func() int {
i++
closure.
return i
}
}

func main() {

We call intSeq, assigning the result (a function) to nextInt := intSeq()


nextInt. This function value captures its own i value,
which will be updated each time we call nextInt.

See the effect of the closure by calling nextInt a few fmt.Println(nextInt())


times. fmt.Println(nextInt())
fmt.Println(nextInt())

To confirm that the state is unique to that particular newInts := intSeq()


function, create and test a new one. fmt.Println(newInts())
}

$ go run closures.go
1
2
3
1

The last feature of functions we’ll look at for now is


recursion.

Next example: Recursion.

by Mark McGranaghan and Eli Bendersky | source | license

You might also like