有函数如下package mainimport "fmt"func intSeq() func() int{i := 0return func() int {
i += 1
return i
}}func main(){nextInt := intSeq()
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
newInts := intSeq()
fmt.Println(newInts())}在intSeq()中,匿名函数里的i和外部环境中的i是同一个吗?还是说外部的i是在栈中,匿名函数的i是在堆中?
1 回答
泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
可以进行一下内存逃逸分析, 执行一下
go run -gcflags '-m -l' demo.go
可以看到输出结果如下:
# command-line-arguments ./demo1.go:7:9: func literal escapes to heap ./demo1.go:7:9: func literal escapes to heap ./demo1.go:8:3: &i escapes to heap ./demo1.go:6:2: moved to heap: i ./demo1.go:15:21: nextInt() escapes to heap ./demo1.go:16:21: nextInt() escapes to heap ./demo1.go:17:21: nextInt() escapes to heap ./demo1.go:20:21: newInts() escapes to heap ./demo1.go:15:13: main ... argument does not escape./demo1.go:16:13: main ... argument does not escape./demo1.go:17:13: main ... argument does not escape./demo1.go:20:13: main ... argument does not escape1231
可以看到&i,i和nextInt函数都从栈空间逃逸到了堆上. &i就是nextInt函数中的那个i.
添加回答
举报
0/150
提交
取消