Exercise: Fibonacci closure

题目
Let's have some fun with functions.

Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers (0, 1, 1, 2, 3, 5, ...).

答案

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
    fib1 := 0 
    fib2 := 1
    return func() int{
        fib2 = fib1 + fib2
        fib1 =  fib2 - fib1
        return fib2 - fib1
    }
}

func main() {
    f := fibonacci()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}

你可能感兴趣的:(Exercise: Fibonacci closure)