在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/GO  網(wǎng)絡(luò)安全/ golang閉包問題

golang閉包問題

有函數(shù)如下
package main

import "fmt"

func intSeq() func() int{

i := 0
return 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()中,匿名函數(shù)里的i和外部環(huán)境中的i是同一個(gè)嗎?還是說外部的i是在棧中,匿名函數(shù)的i是在堆中?

回答
編輯回答
局外人

可以進(jìn)行一下內(nèi)存逃逸分析, 執(zhí)行一下

go run -gcflags '-m -l' demo.go

可以看到輸出結(jié)果如下:


# 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 escape
1
2
3
1

可以看到&i,i和nextInt函數(shù)都從??臻g逃逸到了堆上. &i就是nextInt函數(shù)中的那個(gè)i.

2018年8月23日 05:15