Member-only story

Closure in Golang

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 := 1
f := func() int {
sum := first + second
first, second = second, sum
return 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.

--

--

Simplify Complexity
Simplify Complexity

Written by Simplify Complexity

Golang, Distributed Systems, File Systems, Python, C/C++, Linux

Responses (1)