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

关于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 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿