问题
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