1
votes

Today i was reviewing some code and i found the following behavior:

func main(){
   a := testing()
   fmt.Println(*a)
}

func testing() *int{
   i := 7
   return &i
}

https://go.dev/play/p/Peubn0degBr

OUTPUT: 7

My question is: what is happening here? var i only exists on the scope of testing(). But somehow go lang saves the pointer and understands that it needs that value.

Go is a garbage collected language. You may return addresses of local variables, they (the local variables) will be kept in memory for as long as needed (as long as someone has the pointer). If they may "escape" the function, it will be allocated on the heap (instead of the stack) in the first place. - icza