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

关于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
    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
    }
    
    点赞 评论
  • dongle19863
    dongle19863 2016-12-06 12:11

    Although you have accepted the above answer i'm giving another explanation. The reason why you receive the last value of the loop operation has to do with the Go's lexical scoping. The for loop introduces a new lexical block in which the value is referenced by it's memory address, so by pointer and not by it's value. In order to get the value, you have to de-reference.

    Each time the for loop makes an iteration the value processed is pointing to the same memory address. All the function values created by this loop "capture" and share the same variable - and addressable storage location, not it's value at that particular moment. Thus when the last iteration is finished, the variable holds the value from the final step.

    A much better approach for these kind of operations would be to use goroutines, because in these cases you are not communicating through sharing the same memory address, but you are sharing the memory through communication.

    Here is a more elegant solution using goroutine:

    package main
    
    import (
        "fmt"
    )
    
    func fibonacci(ch chan interface{}, quit chan struct{}) {
        x, y := 1, 1
        for {
            select {
            case ch <- x:
                x, y = y, x+y
                fmt.Println(x , y)
            case <-quit:
                fmt.Println("Quiting...")
                return
            }
        }
    }
    
    func main() {
        ch := make(chan interface{})
        quit := make(chan struct{})
    
        go func() {
            for i := 0; i < 10; i++ {
                <-ch
            }
            quit <- struct{}{}
        }()
    
        fibonacci(ch, quit)
    }
    

    https://play.golang.org/p/oPQgXWyV9u

    点赞 评论

相关推荐