Go's escape analysis and why my function return worked
bonniesimon.in
Go's escape analysis and why my function return worked
1–10 of 76 posts
Re: Go's escape analysis and why my function return worked
#2[deleted]
Re: Go's escape analysis and why my function return worked
#3This seems to be a persistent source of confusion. Escape analysis is just an optimization. You don't need to think about it to understand why your Go code behaves the way it does. Just imagine that everything is allocated on the heap and you won't have any surprises.
Re: Go's escape analysis and why my function return worked
#4This seems to be a persistent source of confusion. Escape analysis is just an optimization. You don't need to think about it to understand why your Go code behaves the way it does. Just imagine that everything is allocated on the heap and you won't have any surprises.
Makes sense. I need to rewire how I think about Go. I should see it how I see JS.
Re: Go's escape analysis and why my function return worked
#5If the functions get inlined (which they might if they're small enough), then the code won't even need to allocate on heap! That's a kind of optimisation that's not really possible without transparent escape analysis.
Re: Go's escape analysis and why my function return worked
#6Go is returning a copy of the slice, in the same way that C would return a copy of an int or struct if you returned it. The danger of C behaviour in this instance is that a stack allocated array decays into a pointer which points to the deallocated memory. Otherwise the behaviour is pretty similar between the languages.
Re: Go's escape analysis and why my function return worked
#7[deleted]
Re: Go's escape analysis and why my function return worked
#8Go is returning a copy of the slice, in the same way that C would return a copy of an int or struct if you returned it. The danger of C behaviour in this instance is that a stack allocated array decays into a pointer which points to the deallocated memory. Otherwise the behaviour is pretty similar between the languages.
I first wrote an answer about how local variables can survive through a pointer, but deleted it because you're right that this Go code doesn't even address locals. It's a regular value copy.
Re: Go's escape analysis and why my function return worked
#9If the variable was defined in the calling function itself, and a pointer was passed, I guess the variable will still be in the heap?
Re: Go's escape analysis and why my function return worked
#10If the variable was defined in the calling function itself, and a pointer was passed, I guess the variable will still be in the heap?
Pointers escape to the heap by default.