logoalt Hacker News

bb88today at 12:19 AM3 repliesview on HN

How does it deal with pointers if everything is stack based? You can't really return a pointer to something on the stack because it could get overwritten between when you return it and when you access it.


Replies

wrstoday at 1:30 AM

Exactly as well as C does, it seems.

    func newPerson() *Person {
        p := Person{Name: "Alice", Age: 30}
        return &p
    }
becomes

    static main_Person* newPerson(void) {
        main_Person p = (main_Person){.Name = so_str("Alice"), .Age = 30};
        return &p;
    }
Quoting the FAQ: "So itself has few safeguards other than the default Go type checking. It will panic on out-of-bounds array access, but it won't stop you from returning a dangling pointer or forgetting to free allocated memory. Most memory-related problems can be caught with AddressSanitizer in modern compilers, so I recommend enabling it during development by adding -fsanitize=address to your CFLAGS."

So saying you get the "safety of Go" is a bit of a stretch.

show 2 replies
zabzonktoday at 12:56 AM

Well, it does say:

"Everything is stack-allocated by default; heap is opt-in through the standard library."

So it supports both stack and heap, and I guess static allocation too.