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 (标签-react native|关键词-镜像源)
  • ¥100 照片生成3D人脸视频
  • ¥15 伪装视频时长问题修改MP4的时长问题,
  • ¥15 JETSON NANO
  • ¥15 VS开发qt时如何在paintgl函数中用pushbutton控制切换纹理
  • ¥20 关于 openpyxl 处理excel文件地问题
  • ¥15 MS中不知道高分子的构型怎么构建模型
  • ¥60 QQOP数据,什么是op数据号,怎么提取op数据!能不能大量提取(语言-c语言)
  • ¥15 matlab代码 关于微分方程和嵌套的分段函数。