A Tour of Go---Exercise: Fibonacci closure
2016-10-04 10:44
597 查看
练习:斐波纳契闭包
https://tour.golang.org/moretypes/26Implement a
fibonaccifunction
that returns a function (a closure) that returns successive fibonacci
numbers (0, 1, 1, 2, 3, 5, ...).
实现一个
fibonacci函数,返回一个函数(一个闭包)可以返回连续的斐波纳契数。
package main
import "fmt"
// fibonacci 函数会返回一个返回 int 的函数。
func fibonacci() func() int {
pre := -1
sum := 1
return func() int {
pre, sum = sum, pre+sum
return sum
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
相关文章推荐
- A Tour of Go: Exercise: Rot13 Reader
- A Tour of Go : Exercise: Fibonacci closure
- A Tour of Go : Advanced Exercise: Complex cube roots
- A Tour of Go: Exercise: Rot13 Reader
- A Tour of Go - Exercise: Equivalent Binary Trees
- A Tour of Go - Exercise: Web Crawler
- 【GoLang笔记】A Tour of Go - Exercise: Web Crawler
- A Tour of Go Exercise: Maps
- A Tour of Go : Exercise: Loops and Functions
- 【GoLang笔记】A Tour of Go - Exercise: Equivalent Binary Trees
- A Tour of Go : Exercise: Maps
- 【GoLang笔记】A Tour of Go - Exercise: Images
- A Tour of Go Exercise: Images
- A Tour of Go : Exercise: Slices
- go官网教程A Tour of Go
- A Tour of Go Multiple results
- A Tour of Go Struct Literals
- exercise.tour.go google的go官方教程答案
- A Tour of Go Named results
- A Tour of Go Arrays