Recently I came across something interesting in Go. I wrote the following code to read logs from a log file in the server. func readLogsFromPartition(partition int) []LogEntry { var logs []LogEntry logs = ReadFromFile() return logs } func main() { logs := readLogsFromPartition(1) } I compiled the program and ran it, and it worked. But after I took a step back and looked at it, I couldn't make sense of why it worked. Why am I able to return a value that was created on the local function back to the main function? If you can't seem to understand why I'm confused, then I'll explain some background. Before my Go phase, I was trying to get back into writing C. And I had a few head scratching days of understanding the stack vs the heap. From my understanding of C/C++, the above code would blow up. In C, you can't assign a value in a local function and then return it (if the value is a pointer). This is because when the function returns, all the stack values are destroyed, and hence the returned value will be replaced with garbage value. Lets see an equivalent example of this in C: #include <stdio.h> int* readLogsFromPartition() { int logs[5] = {101, 102, 103, 104, 105}; return logs; } int main() { int* logs = readLogsFromPartition(); printf("First log: %d\n", logs[0]); printf("Reading logs...\n"); for (int i = 0; i < 5; i++) { printf("Log %d: %d\n", i, logs[i]); } return 0; } As you can see, logs is a local array that we have defined in readLogsFromPartition. It will be initialized on the stack. Thus when the function readLogsFromPartition returns, internally the entry associated with readLogsFromPartition on the stack will be popped and cleared. So in the main function, we won't have a accurate value of logs. Instead we'll get garbage values. In C, to avoid this, you'd initialize the variable in the calling function (on stack or heap) and then pass a pointer to the function. Then in the function, you'd dereference the variable and assign the value to it. #include <stdio....
First seen: 2025-12-11 09:36
Last seen: 2025-12-11 16:38