美文网首页我爱编程
利用Golang的闭包实现斐波那契

利用Golang的闭包实现斐波那契

作者: insanus | 来源:发表于2018-05-25 13:55 被阅读0次
package main

import "fmt"

func main() {
    function := Fibonacci()
    for i := 1; i <= 5; i ++ {
        fmt.Println(function())
    }
}

func Fibonacci() func() int {
    f1 := 0
    f2 := 1
    return func() int {
        temp := f2
        f2 = f1 + f2
        f1 = temp
        return temp
    }
}
/*
output:
1
1
2
3
5
*/

相关文章

网友评论

    本文标题:利用Golang的闭包实现斐波那契

    本文链接:https://www.haomeiwen.com/subject/mnoyjftx.html