Hacker News new | ask | show | jobs
by odo1242 12 days ago
The answer is apparently "you don't":

- Everything in the language is statically allocated or stack-allocated. You have to call a malloc / free function to get heap allocated things

- The language is not memory safe (you can't return slices, pointers, or interface types from a function if the thing was created inside the function, unless you used heap allocation)

- Interfaces (the only variable size struct Go has) are implemented by creating a struct of function pointers. Arrays and maps (the non-struct variable size types) are implemented as stack-only and maps are limited to 1024 keys. You can opt into heap-based arrays / maps in the standard library to bypass this.

2 comments

It sounds incredibly dangerous in the hands of a usual go programmer who has no idea what the difference between the stack and the heap is.
Been a while since I used go but I remember it being kind of uniquely hard to tell? Like a struct is on the stack, but a *struct is maybe on the heap, depending on escape analysis?
In go you don’t need to care, the GC will take care of allocations on the heap and the runtime will choose when something should go on the stack. That’s the problem: in this other language it’s suicidal to program as if it was the same as Go as you will just make huge mistakes like returning a pointer to a local variable.
isn't it the exact same as C in this regard? The pointer being on the stack or not depends how it was originally allocated.
In C you explicitly malloc things onto the heap. In go, taking the address of something maybe allocates on the heap, or maybe not if escape analysis can keep it on the stack.
So much for "Go's safety" in the quote above. Ok, it doesn't explicitly say memory safety, but what other safety could if be referring to?
comparing it with c? thread safety maybe?
As far as I understand co-routines help don't really help with memory shared across go-routines. They only help in the fact you need to manage spawning and joining threads, making it easier to do stuff in parallel. But they don't provide thread-safety.

edit: I suppose you don't get segfaults or buffer overflows and the sort in go for accessing memory in a parallel context, you get recoverable panics. But that is still not really thread safety in my opinion, it is memory safety.

The language also does not support goroutines, locks, or channels, except through using the C threading libraries.

(I think the original author meant type safety when they made that statement. Though it still doesn't make all that much sense to me)

it could also be Typesafe at compile time