Closures
A function literal can use the variables of the code around it:
package main
import "fmt"
func main() {
count := 0
increment := func() {
count++
}
increment()
increment()
fmt.Println(count)
}
Output:
2
increment has no parameters, yet it changes count, a variable of main. It does not get a copy of count, the way a parameter would. It uses the very same variable, so after two calls main sees 2. A function that uses a variable from outside itself is called a closure.
Keeping a variable alive
A function can also return a closure. Here makeCounter returns a function that counts:
package main
import "fmt"
func makeCounter() func() int {
count := 0
return func() int {
count++
return count
}
}
func main() {
next := makeCounter()
fmt.Println(next())
fmt.Println(next())
fmt.Println(next())
}
Output:
1
2
3
The return type of makeCounter is func() int: a function that takes nothing and returns an int. The return line returns a function literal of exactly that type.
Now think about count. It is a local variable of makeCounter, and the Variable Scope lesson said a variable is gone when its block ends. But the returned function still uses count. So Go keeps count alive for as long as the closure exists. Every call of next() adds 1 to that same count, which is why the output goes 1, 2, 3.
Each call makes a new variable
Each time makeCounter runs, its body runs again, and count := 0 makes a brand new variable. So two counters do not share a count:
package main
import "fmt"
func makeCounter() func() int {
count := 0
return func() int {
count++
return count
}
}
func main() {
a := makeCounter()
b := makeCounter()
fmt.Println("a:", a())
fmt.Println("a:", a())
fmt.Println("b:", b())
fmt.Println("a:", a())
}
Output:
a: 1
a: 2
b: 1
a: 3
b starts at 1 even though a was already at 2. Each closure keeps its own count.
This is the main reason to use a closure. It keeps a value between calls, like a package-level variable would. But only the closure can reach that value, so no other code can change it by mistake.
Using parameters in a closure
A closure can also use the parameters of the function that made it. makeAdder returns a function that adds a fixed number:
package main
import "fmt"
func makeAdder(n int) func(int) int {
return func(x int) int {
return x + n
}
}
func main() {
addFive := makeAdder(5)
addTen := makeAdder(10)
fmt.Println(addFive(1))
fmt.Println(addTen(1))
}
Output:
6
11
addFive remembers n as 5, and addTen remembers its own n as 10.
In the exercise, complete the function that makeCounter returns. Each call adds step to the count and returns the new count.