logoalt Hacker News

9rxlast Thursday at 2:45 PM2 repliesview on HN

> 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);
    }

Replies

simioneslast Thursday at 2:58 PM

The point the GP was making was that the following Go snippet:

  func foo() {
    x := []int { 1 }
    //SNIP 
  }
Could translate to C either as:

  void foo() { 
    int* x = malloc(1 * sizeof(int));
    x[0] = 1;
    //...
  }
Or as

  void foo() { 
    int data[1] = {1};
    int *x = data;
    //...
  }
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.
show 1 reply
foldrlast Thursday at 5:21 PM

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.)

show 1 reply