A Tour of Go Exercise: Fibonacci closure

时间:2021-03-05 07:35:55

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 {
before :=
now :=
return func() int {
if before == {
before++
return before
}
if now == {
now++
return now
}
temp := now
now = before + now
before = temp
return now
}
} func main() {
f := fibonacci()
for i := ; i < ; i++ {
fmt.Println(f())
}
}