Skip to content

Instantly share code, notes, and snippets.

@pstoll
Created November 18, 2012 19:45
Show Gist options
  • Select an option

  • Save pstoll/4107103 to your computer and use it in GitHub Desktop.

Select an option

Save pstoll/4107103 to your computer and use it in GitHub Desktop.
Golang tour 48 fibanacci using a closure
// http://tour.golang.org/#48
//
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
prev := 0;
cur := 1
f := func () int {
s := prev + cur
// nice - swapping via ordered tuple assignment/unpacking
prev, cur= cur, s
return s
}
return f
}
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