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.
> This seems to be a persistent source of confusion.
Why? It is the same as in C.
#include <stdio.h>
#include <stdlib.h>
struct slice {
int *data;
size_t len;
size_t cap;
};
struct slice readLogsFromPartition() {
int *data = malloc(2);
data[0] = 1;
data[1] = 2;
return (struct slice){ data, 2, 2 };
}
int main() {
struct slice s = readLogsFromPartition();
for (int i = 0; i < s.len; i++) {
printf("%d\n", s.data[i]);
}
free(s.data);
}
I am currently learning go and your comment made me sort some things out, but probably in a counterintuitive way.
Assuming to everything allocates on the heap, will solve this specific confusion.
My understanding is that C will let you crash quite fast if the stack becomes too large, go will dynamically grow the stack as needed. So it's possible to think you're working on the heap, but you are actually threshing the runtime with expensive stack grow calls. Go certainly tries to be smart about it with various strategies, but a rapid stack grow rate will have it's cost.