func main() { for i := 1; i < 30; i++ { fmt.Println(Fibonacci(i)) } } func Fibonacci(n int) int { if n == 0 { return 0 } f := fib() var res int for i := 0; i < n; i++ { res = f() } return res } func fib() func() int { i, j := 0, 1 //局部变量i,j属于函数fib()
return func() int {
i, j = j, i+j
return i
}
}
结果:
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229