Skip to content

Instantly share code, notes, and snippets.

@zonggen
Created June 18, 2018 00:36
Show Gist options
  • Save zonggen/5b2de30955ea4aaf14a02bbc889dcca9 to your computer and use it in GitHub Desktop.
Save zonggen/5b2de30955ea4aaf14a02bbc889dcca9 to your computer and use it in GitHub Desktop.
A Tour of Go - Fibonacci Closure
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
now := 0
next := 1
return func() int {
result := now
temp := next
next = next + now
now = temp
return result
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
@ubshreenath
Copy link

Back in my school days this solution would have me totally perplexed on how this actually worked. C++ back then had no support for Lambdas or Closures. Only when I learnt JavaScript did I learn the magic of Closures and now can understand the beauty of this solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment