> 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);
}What confuses people is
int *foo(void) {
int x = 99;
return &x; // bad idea
}
vs. func foo() *int {
x := 99
return &x // fine
}
They think that Go, like C, will allocate x on the stack, and that returning a pointer to the value will therefore be invalid.(Pedants: I'm aware that the official distinction in C is between automatic and non-automatic storage.)
The point the GP was making was that the following Go snippet:
Could translate to C either as: Or as Depending on the content of //SNIP. However, some people think that the semantics can also match the semantics of the second version in C - when in fact the semantics of the Go code always match the first version, even when the actual implementation is the second version.