【发布时间】:2021-03-07 20:33:15
【问题描述】:
关于此代码的问题。为什么变量会逃到堆中
func main() {
port := "8080"
host := "localhost:"
connection := host + port
fmt.Println(connection)
}
gorun -gcflags "-m -l" main.go
# command-line-arguments
./main.go:12:21: host + port escapes to heap
./main.go:13:13: ... argument does not escape
./main.go:13:13: connection escapes to heap
我发现如果使用fmt.Sprintf 它也会导致变量逃逸到堆中
【问题讨论】:
-
这是一个实现细节。其他编译器或编译器版本可能不会在这里使用堆。
标签: go memory-management stack heap-memory escape-analysis