请教大神,关于GO中的闭包如何使用,最好能有个例子,谢谢了~
使用go build -gcflags -m ./func.go可以看到这样的信息
# command-line-arguments
./func.go:9: can inline func·001
./func.go:9: func literal escapes to heap
./func.go:8: moved to heap: i ->显示会将闭包函数所引用的空间移到堆中。避免以后的闭包调用找不到目标。
./func.go:10: &i escapes to heap
./func.go:11: func literal escapes to heap
./func.go:12: &i escapes to heap
./func.go:12: func·002 ... argument does not escape
#5
更多评论
保存到func.go
```go
package main
import (
"fmt"
)
func Func() (func(), func()) {
i := 10
return func() {
i++
}, func() {
fmt.Println(i)
}
}
func main() {
Add, Print := Func()
for i := 0; i < 10; i++ {
Add()
}
Print()
}
```
使用go build -gcflags -m ./func.go可以看到这样的信息
# command-line-arguments
./func.go:9: can inline func·001
./func.go:9: func literal escapes to heap
./func.go:8: moved to heap: i ->显示会将闭包函数所引用的空间移到堆中。避免以后的闭包调用找不到目标。
./func.go:10: &i escapes to heap
./func.go:11: func literal escapes to heap
./func.go:12: &i escapes to heap
./func.go:12: func·002 ... argument does not escape
#2