Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.