Skip to content

Instantly share code, notes, and snippets.

@MattSurabian
Created July 14, 2013 05:32
Show Gist options
  • Save MattSurabian/5993310 to your computer and use it in GitHub Desktop.
Save MattSurabian/5993310 to your computer and use it in GitHub Desktop.
Implementation of a Fibonacci Closure in Go. Part of the Go tour: http://tour.golang.org/#43
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
var m1, m2 int
return func() int {
res := m1 + m2
m2 = m1
m1 = res
if res == 0 {
m2 = 1 // Because printing the full sequence is hot
}
return res
}
}
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