go-tour/exercise-fibonacci-closure.go

26 lines
380 B
Go
Raw Permalink Normal View History

2020-02-05 03:44:36 +00:00
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
x := 0
y := 1
z := 0
return func() int {
z, x, y = x, y, x + y
if z == 0 {
return 0
}
return z
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}