Question about this code . why variables escape to heap
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
And I found if use fmt.Sprintf
it also cause the variables escape to heap
It's not the concatenation but the call to the
fmt
package that causes the escape.If you call the builtin
println()
function instead, it won't:Running
go run -gcflags "-m -l" main.go
:In case of
fmt.Println()
the compiler can't guarantee what will happen to the passed value, so it puts it on the heap.