Open
Description
package main
var b *int
func main() {
testStack()
}
func testStack() {
var x int = 1
//b = &x
println(&x)
testLargeX(&x)
println(&x)
}
func testLargeX(x *int) {
var a = make([]int, 2000)
for i := 0; i < len(a); i++ {
a[i] = 1
}
println(a[1])
println(x, *x)
}
这个程序输出为:
0xc000042770
1
0xc000107f70 1
0xc000107f70
x这个栈上变量因为栈空间的扩张,栈在另一个地方重新分配内存,x的地址变化了
如果把注释的那行 b = &x放开
widon@widon-deepin:~/golang/src/test/stackTest$ go build -gcflags="-m"
test/stackTest
./1.go:9:6: can inline testStack
./1.go:5:6: can inline main
./1.go:6:11: inlining call to testStack
./1.go:17:17: x does not escape
./1.go:18:14: make([]int, 2000) does not escape
./1.go:6:11: moved to heap: x
./1.go:10:6: moved to heap: x
x就会在堆上分配内存,那x的地址就不会变化了