when is a local var destroyed

tags: learning go programming

content

func myFunc() *int {
	x := 1
	return &x
}
b := myFunc()
  • in this code, my initial understanding is that: x is a local variable in the stack frame, when the function returns, x is destroyed and b points to invalid/garbage memory
  • this is true in C
  • but in go, when &x is returned, it’s moved from stack to heap, so that the local variable outlives the function

up

down

reference