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 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同