Go variables escape to the heap when using the add operator to concatenate strings

1k views Asked by At

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

1

There are 1 answers

3
icza On

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:

println(connection)

Running go run -gcflags "-m -l" main.go:

# command-line-arguments
./main.go:12:21: host + port does not escape
localhost:8080

In case of fmt.Println() the compiler can't guarantee what will happen to the passed value, so it puts it on the heap.