Exercise: Fibonacci closure
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Exercise: Fibonacci closure相关的知识,希望对你有一定的参考价值。
Exercise: Fibonacci closure
题目:
Let‘s have some fun with functions. Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers (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 { a, b, c := 0, 1, 0 return func () int { c, a, b = a, b, a+b return c } } func main() { f := fibonacci() for i := 0; i < 10; i++ { fmt.Println(f()) } }
运行结果:
0 1 1 2 3 5 8 13 21 34
以上是关于Exercise: Fibonacci closure的主要内容,如果未能解决你的问题,请参考以下文章