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

huangapple go评论81阅读模式
英文:

golang closure(anonymous function)catch wrong parameter`s value

问题

看到你的代码了:

package main

import "fmt"

func main() {
    i := 10

    closure1 := func() {
        fmt.Printf("闭包函数,i的值为:%d\n", i)
        i = 15
    }

    closure1()

    fmt.Printf("在main函数中,i的值为:%d\n", i)

    closure2 := func(x int) {
        fmt.Printf("函数调用,传递参数,i的值为:%d\n", x)
    }

    i = 20

    closure1()
    closure2(i)
}

我认为closure2的输出应该是20,但实际结果是15,我不知道为什么?请问有人可以帮助我吗?请查看我在代码中的注释,提前谢谢。

英文:

see test code:

package main

import "fmt"

func main() {
    i := 10

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

    closure1()

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

    closure2 := func(x int) {
        fmt.Printf("function call, pass parameter, i: %d\n", 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.

答案1

得分: 2

问题在于当你调用closure1()时,你首先将i赋值为15,然后在closure two中打印它。你在将i赋值为20之后才执行closure1(),这就是问题所在。以下是修复你的问题的代码:

package main

import "fmt"

func main() {
    i := 10

    closure1 := func() {
        fmt.Printf("闭包,i:%d\n", i)
        i = 15
    }

    closure1()

    fmt.Printf("在main函数中,i:%d\n", i)

    closure2 := func(x int) {
        fmt.Printf("函数调用,传递参数,i:%d\n", x)
    }

    closure1()
    i = 20 // 现在将其重新赋值为20... 所以下面的结果将变为20...
    closure2(i)
}

你看到问题了吗?

英文:

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\n", i)
        i = 15
    }

    closure1()

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

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

   

    closure1()
    i = 20 // Now it assigns it back to 20.. So the result below will become 20...
    closure2(i)
}

You see your problem?

答案2

得分: 0

closure1的最后一行将i设置为15。这个i属于main()的上下文。

main的倒数第二行再次调用closure1()。所以来自main的i再次被设置为15。

英文:

The last line of closure1 sets i to 15. This i belongs to the main() context.

The next to last line of main calls closure1() again. So the i from main is set to 15 again.

huangapple
  • 本文由 发表于 2016年3月22日 18:46:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/36152294.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定