Skip to content

Instantly share code, notes, and snippets.

@gerrywastaken
Created October 26, 2020 22:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerrywastaken/d662b512a84770b085baee73a542701a to your computer and use it in GitHub Desktop.
Save gerrywastaken/d662b512a84770b085baee73a542701a to your computer and use it in GitHub Desktop.
Answer to Exercise: Fibonacci closure in A Tour of Go
# An answer to https://tour.golang.org/moretypes/26
# This is a bit more readable than other examples that I found online
# Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers (0, 1, 1, 2, 3, 5, ...).
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
prev, current := -1, 1
return func() int {
prev, current = current, prev+current
return current
}
}
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