Skip to content

Instantly share code, notes, and snippets.

@yixiaoyx
Last active May 26, 2019 02:33
Show Gist options
  • Save yixiaoyx/3d3de6251a0720b8f2356672df4f71da to your computer and use it in GitHub Desktop.
Save yixiaoyx/3d3de6251a0720b8f2356672df4f71da to your computer and use it in GitHub Desktop.
A Tour of Go exercise
// generates a series of fibonacci numbers
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
// my solution here
func fibonacci() func() int {
var pre = -2
var sum = 1
return func() int {
switch pre {
case -2:
pre++
return 0
case -1:
pre++
return 1
default:
var tmp = sum
sum += pre
pre = tmp
return sum
}
}
}
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