Live data from Hacker News

Go's escape analysis and why my function return worked

bonniesimon.in

1–10 of 76 posts

Re: Go's escape analysis and why my function return worked

#3
This 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

#4
post #3

This 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

#6
Go 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

#8

Go 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.
Post reply on HN