donglong7338 2016-12-06 08:18
浏览 187
已采纳

关于Golang中的lambda函数/闭包的一些困惑

package main
import (
    "fmt"
)
func main(){
    f,val,val1:=fibonacci()
    fmt.Println(val,val1)
    for i:=0;i<=10;i++ {
        fmt.Println(f(i),val,val1)
    }
    _,val,val1=fibonacci()
    fmt.Println(val,val1)
}
func fibonacci()(func(n int)int,int,int){
    var val int
    var val1 int
    f:=func(n int)int{
        if n==0||n==1{
            val,val1=1,1
        }else{
            val,val1=val+val1,val
        }
        return val
    }
    fmt.Println("fibonacci val =",val,"val1 =",val1)
    return f,val,val1
}

Here is my code on sloving fibonacci without using recursion when I read about lambda function/closure. And the Go Documentary says a closure will capture some external state. My understanding is the closure will keep a copy of state of the function which it is declared. These states are just copies whatever I do on them won't modify the original, is that so?

  • 写回答

2条回答 默认 最新

  • dongpinken0498 2016-12-06 09:19
    关注

    from your test code here: https://play.golang.org/p/pajT2bAIe2

    your fibonacci function is working out the nth numbers in the sequence provided it's called in an incremental fashion as you are doing. but the values you return from the initial call to fibonacci are not pointers (or references) to those integer values they are just the values of those integers at that time, think of them as being copied out of the function, try using integer pointers instead like this: https://play.golang.org/p/-vLja7Fpsq

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        f, val, val1 := fibonacci()
        fmt.Println(val, val1)
        for i := 0; i <= 10; i++ {
            fmt.Println(f(i), *val, *val1) //dereference the pointer to get its value at the current time
        }
        _, val, val1 = fibonacci()
        fmt.Println(*val, *val1)
    }
    func fibonacci() (func(n int) int, *int, *int) {
        var val int
        var val1 int
        f := func(n int) int {
            if n == 0 || n == 1 {
                val, val1 = 1, 1
            } else {
                val, val1 = val+val1, val
            }
            return val
        }
        fmt.Println("fibonacci val =", val, "val1 =", val1)
        return f, &val, &val1 // return pointers to the closured values instead of just the values
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Mac虚拟机安装Windows,Windows中用idea跑项目,报错process finished with exit code -1073741819(0xc0000005) 如何解决?
  • ¥15 关于python爬虫返回js数据结构的处理
  • ¥15 ubuntu所用stm32标准库开发烧录没反映
  • ¥15 运维工程师(在职人员回答)
  • ¥15 Kmeans的趋势分析有会的吗
  • ¥20 R语言单细胞测序 对seurat对象进行标准化时出现问题
  • ¥15 Anaconda navigator updateor一直更新
  • ¥15 请问如何在matlab里使用raven工具?
  • ¥100 关于ios手游充值到一定金额,再点充值提示公众号的问题。
  • ¥15 求一个stm32串口控制程序