Skip to content

Instantly share code, notes, and snippets.

@guoxingx
Created May 18, 2018 07:55
Show Gist options
  • Save guoxingx/4c1e7f90ebc57385d0f9ab08cb35eaca to your computer and use it in GitHub Desktop.
Save guoxingx/4c1e7f90ebc57385d0f9ab08cb35eaca 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 {
a, b, n := 0, 1, 0
return func() int {
a, b, n = b, a + b, n + 1
return a
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment