I would like to know about the reuse of stack space in Go.
When writing code like the following, we can see that the variable x is allocated to the same stack space in each iteration, and its value is updated:
package main
import "time"
func main() {
for range 3 {
x := time.Now()
println(&x) // output same address for each iteration
println(x.UnixNano()) // output different value for each iteration
}
}
On the other hand, in the following code, stack space reuse does not occur, and different addresses are assigned:
package main
import "time"
func main() {
{
x := time.Now()
println(&x) // 0x1400007cf20
}
{
x := time.Now()
println(&x) // 0x1400007cf08
}
}
My question is, under what circumstances does the Go compiler attempt to reuse stack space? Additionally, where in the source code can this mechanism be understood?
I found a commit that seems to be related to this behavior, but I was unable to understand it.
https://github.com/golang/go/commit/366dcc4529d09c31f7b0df65003792022bc5ec09
Could you please help me with this question?
user8729163 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.