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.
bonniesimon•5d ago
Makes sense. I need to rewire how I think about Go. I should see it how I see JS.
nasretdinov•1h ago
If 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.
samdoesnothing•31m ago
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.
debugnik•21m ago
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.
potato-peeler•2m ago
If the variable was defined in the calling function itself, and a pointer was passed, I guess the variable will still be in the heap?
foldr•5d ago
bonniesimon•5d ago