看到測試代碼:golang關閉(匿名函數)抓錯parameter`s值
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)
}
我覺得closure2的輸出應該是20,但實際結果是15,我不知道爲什麼? ??? 有人可以幫助我,請在我的代碼中看到我的評論,提前致謝。
''''''''在'closure1'結尾分配了15個,你在調用'closure2'之前調用。所以你通過15'clos2' –
[陷阱與閉合在去](http://www.goinggo.net/2014/06/pitfalls-with-closures-in-go.html) –
我看到,golang關閉catch對i的引用,而不是快照值,我明白了,非常感謝。 – scott