Skip to content

Instantly share code, notes, and snippets.

@VojtechVitek
Created April 14, 2014 10:44
Show Gist options
  • Select an option

  • Save VojtechVitek/10636899 to your computer and use it in GitHub Desktop.

Select an option

Save VojtechVitek/10636899 to your computer and use it in GitHub Desktop.
A Tour of Go | Exercise: Fibonacci closure
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
fib := 0
return func() int {
first, second := 0, 1
for i := 0; i < fib; i++ {
first, second = second, first + second
}
fib++
return first
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
f2 := fibonacci()
for i := 0; i < 20; i++ {
fmt.Println(f2())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment