package main import ( "fmt" ) func main() { var fs = [4]func(){} for i := 0; i < 4; i++ { defer fmt.Println("defer i = ", i) defer func() { fmt.Println("defer_closure i = ", i) }() fs[i] = func() { fmt.Println("closure i = ", i) } } for _, f := range fs { f() } }
这两天有时间学习了一下go语言。挺有趣的。
上面这段代码是关于closure和defer的用法。
go语言支持闭包,如果你在闭包函数中使用了上层函数的变量,那么这个变量的一个内存地址会记录到这个闭包中,当你调用这个闭包函数的时候,这个变量的值会直接去记录的内存地址里取,所以就得到了这个打印:
closure i = 4 closure i = 4 closure i = 4 closure i = 4 defer_closure i = 4 defer i = 3 defer_closure i = 4 defer i = 2 defer_closure i = 4 defer i = 1 defer_closure i = 4 defer i = 0
有疑问加站长微信联系(非本文作者)