I'm reading a book called The Go Programming Language, and in the 2nd chapter about pointers the following is written
It is perfectly safe for a function to return the address of a local variable. For instance, in the code below, the local variable v created by this particular call to f will remain in existence even after the call has returned, and the pointer p will still refer to it:
var p = f()
func f() *int {
v := 1
return &v
}
I totally don't get this, a local variable is supposed to be destroyed after the function execution. Is it because maybe v is allocated on the heap. I know in C if you allocate space using malloc it won't be destroyed after function execution because it's on the heap.
Go isn't C. Despite similarities, it is much higher-level. It utilizes a complete runtime with a green thread scheduler and garbage-collecting memory manager. It will never collect memory so long as it has live references.
The Go compiler includes a stage called "escape analysis", where it tracks each variable to see if it "escapes" the function in which it is declared. Any value that can escape is allocated on the heap and managed by garbage collection; otherwise, it is (usually) allocated on the stack.
You can find more information on the subject:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With