Go's escape analysis and why my function return worked
bonniesimon.in·4d·
Discuss: Hacker News
🧠Separation Logic
Preview
Report Post

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 // Creating an innocent slice
logs = ReadFromFile()

return logs // Returning the slice
}

func main() {
logs := readLogsFromPartition(1) // Using the slice in the main func
}

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 scrat…

Similar Posts

Loading similar posts...