doutong7216 2016-03-22 10:46
浏览 102
已采纳

golang闭包(匿名函数)捕获错误的参数值

see test code:

package main

import "fmt"

func main() {
    i := 10

    closure1 := func() {
        fmt.Printf("closure, i: %d
", i)
        i = 15
    }

    closure1()

    fmt.Printf("in main, i: %d
", i)

    closure2 := func(x int) {
        fmt.Printf("function call, pass parameter, i: %d
", x)
    }

    i = 20

    closure1()
    closure2(i)
}

I think the output of the closure2 should be 20, but the real result is 15, i do not know why???? anybody can help me , please see my comment in my code, thanks in advance.

  • 写回答

2条回答 默认 最新

  • duan20081202 2016-03-22 12:04
    关注

    The problem is that your first assigning i to 15 when your calling closure1() And then closure two you print it.. Your doing closure1() after assigning i to 20.. Thats the problem, this should fix your problem:

    package main
    
    import "fmt"
    
    func main() {
        i := 10
    
        closure1 := func() {
            fmt.Printf("closure, i: %d
    ", i)
            i = 15
        }
    
        closure1()
    
        fmt.Printf("in main, i: %d
    ", i)
    
        closure2 := func(x int) {
            fmt.Printf("function call, pass parameter, i: %d
    ", x)
        }
    
    
    
        closure1()
        i = 20 // Now it assigns it back to 20.. So the result below will become 20...
        closure2(i)
    }
    

    You see your problem?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?