Skip to content

Instantly share code, notes, and snippets.

@ifreesec
Last active July 17, 2018 09:03
Show Gist options
  • Save ifreesec/6c3582916aae8ec32f92613b48c7c74f to your computer and use it in GitHub Desktop.
Save ifreesec/6c3582916aae8ec32f92613b48c7c74f to your computer and use it in GitHub Desktop.
go 语言之旅中的练习——斐波纳契闭包的一种实现方式
//实现一个 fibonacci 函数,它返回一个函数(闭包),该闭包返回一个斐波纳契数列 `(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 {
pre, next := 0, 1
return func() int {
pre, next = next, pre + next
return next - pre
}
}
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