关于此代码的问题。为什么变量转义到堆
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,也会导致变量转义到堆
发布于 2020-11-25 09:13:35
导致转义的不是串联,而是对fmt包的调用。
如果调用内置的println()函数,它将不会:
println(connection)运行go run -gcflags "-m -l" main.go
# command-line-arguments
./main.go:12:21: host + port does not escape
localhost:8080在fmt.Println()的情况下,编译器不能保证传递的值会发生什么,所以它将其放在堆上。
https://stackoverflow.com/questions/64997017
复制相似问题