Golang Closure Exercise
I always had a question, if Golang does not have the static variable, how could it gracefully handle long lifetime variables except using global variables?
Until last night, I saw this Exercise: Fibonacci closure in A tour of Go. I have to admit I am not a fan of closure, sometimes it makes easy logic complex. But it is still great for learning.
Exercise: Fibonacci closure
Let’s have some fun with functions.
Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers (0, 1, 1, 2, 3, 5, …).
|
|
Usually, it is easy to choose the initial values of first
and second
, if the sequence starts from 1
. What if the sequence starts from 0
, why 1
and 0
?
Let’s take a close look at the Fibonacci sequence.
Base on the formula, it could also be extended to negative index. So it is easy to choose the initial value as $F_{-1}$ and $F_{0}$.
A typical C++ implementation would not need closure, it can be implemented by static variables. It is much more straightforward, although it does not have the ability to leverage the multiple return values like first, second = second, first + second
in Golang.
|
|