Let's have some fun with functions.
Implement a fibonacci
function that returns a function (a closure) that returns successive fibonacci numbers.
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
pre := 0
now := 1
return func() int {
now = pre + now
pre = now - pre
return pre
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
有疑问加站长微信联系(非本文作者)