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

匆匆过客 提交于 2019-12-23 02:47:08

问题


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:


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:


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.



来源:https://stackoverflow.com/questions/36152294/golang-closureanonymous-functioncatch-wrong-parameters-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!