Skip to content

Instantly share code, notes, and snippets.

@waddles
Created February 12, 2015 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waddles/53e06925227a796fa932 to your computer and use it in GitHub Desktop.
Save waddles/53e06925227a796fa932 to your computer and use it in GitHub Desktop.
Go Tour Exercise on Closures - a Fibonacci sequence generator - http://tour.golang.org/moretypes/22
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
seq := []int{0,1}
i := 0
return func() int {
seq = append(seq, seq[i] + seq[i + 1])
i++
return seq[i - 1]
}
}
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