Member-only story
Closure in Golang
Apr 27, 2021
A closure shares its state across calls.
The following code implements the Fibonacci series from Tour of Go.
https://tour.golang.org/moretypes/26
package mainimport "fmt"// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
first := 0
second := 1f := func() int {
sum := first + second
first, second = second, sumreturn sum
}return f
}func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
The interesting thing to note is that function f
is sharing its state across calls.
the state constitutes first
and second
.
On each call of the closure, the previous values of the variables are available.